Below is a SQL Server cheat sheet that includes common SQL queries and commands used in Microsoft SQL Server:
Connecting to SQL Server
-- Connect to SQL Server
USE master;
GO
Database Operations
-- Create a Database
CREATE DATABASE YourDatabaseName;
-- Use a Database
USE YourDatabaseName;
-- Drop a Database
DROP DATABASE YourDatabaseName;
Table Operations
-- Create a Table
CREATE TABLE YourTableName (
Column1 DataType,
Column2 DataType,
...
);
-- Drop a Table
DROP TABLE YourTableName;
Data Manipulation
-- Insert Data
INSERT INTO YourTableName (Column1, Column2, ...) VALUES (Value1, Value2, ...);
-- Update Data
UPDATE YourTableName SET Column1 = NewValue WHERE Condition;
-- Delete Data
DELETE FROM YourTableName WHERE Condition;
Querying Data
-- Select All Rows
SELECT * FROM YourTableName;
-- Select Specific Columns
SELECT Column1, Column2 FROM YourTableName;
-- Filter Data
SELECT * FROM YourTableName WHERE Condition;
-- Order Data
SELECT * FROM YourTableName ORDER BY Column1 ASC;
-- Join Tables
SELECT t1.Column1, t2.Column2 FROM Table1 t1 JOIN Table2 t2 ON t1.JoinColumn = t2.JoinColumn;
Aggregate Functions
-- Count Rows
SELECT COUNT(*) FROM YourTableName;
-- Sum of a Column
SELECT SUM(Column1) FROM YourTableName;
-- Average of a Column
SELECT AVG(Column1) FROM YourTableName;
-- Maximum Value
SELECT MAX(Column1) FROM YourTableName;
Grouping Data
-- Group by Column
SELECT Column1, COUNT(*) FROM YourTableName GROUP BY Column1;
Stored Procedures
-- Create a Stored Procedure
CREATE PROCEDURE YourStoredProcedureName
AS
BEGIN
-- SQL Statements
END;
-- Execute a Stored Procedure
EXEC YourStoredProcedureName;
Indexing
-- Create an Index
CREATE INDEX YourIndexName ON YourTableName (Column1, Column2);
-- Drop an Index
DROP INDEX YourIndexName ON YourTableName;
Backup and Restore
-- Backup Database
BACKUP DATABASE YourDatabaseName TO DISK = 'C:\Path\To\BackupFile.bak';
-- Restore Database
RESTORE DATABASE YourDatabaseName FROM DISK = 'C:\Path\To\BackupFile.bak';
Security
-- Create a User
CREATE LOGIN YourUserName WITH PASSWORD = 'YourPassword';
-- Grant Permissions
USE YourDatabaseName;
CREATE USER YourUserName FOR LOGIN YourUserName;
GRANT SELECT, INSERT, UPDATE, DELETE ON YourTableName TO YourUserName;
This cheat sheet covers fundamental SQL Server commands. Modify the commands based on your specific requirements and always adhere to best practices for security and performance.