SQL Server Cheatsheet

Quick reference guide for SQL Server database operations

Introduction to SQL

SQL (Structured Query Language) is the standard language for managing relational databases.

SQL Command Types
  • DDL: Data Definition Language (CREATE, ALTER, DROP)
  • DML: Data Manipulation Language (INSERT, UPDATE, DELETE)
  • DQL: Data Query Language (SELECT)
  • DCL: Data Control Language (GRANT, REVOKE)
  • TCL: Transaction Control Language (COMMIT, ROLLBACK)
Basic Example
SELECT TOP 10 * FROM customers 
WHERE country = 'USA' 
ORDER BY last_name;

Setting Up SQL Server Environment

Installation
  • SQL Server Express Edition
  • SQL Server Management Studio (SSMS)
  • Azure Data Studio
Online Tools
  • Azure SQL Database
  • SQL Fiddle (SQL Server mode)
  • DB Fiddle (SQL Server mode)
IDEs
  • SQL Server Management Studio
  • Azure Data Studio
  • Visual Studio with SQL Server Data Tools
  • DBeaver

Schema and Table Operations

User/Schema Creation
CREATE LOGIN my_user WITH PASSWORD = 'password';
CREATE USER my_user FOR LOGIN my_user;
ALTER USER my_user WITH DEFAULT_SCHEMA = dbo;
GRANT SELECT, INSERT, UPDATE, DELETE TO my_user;
Table Creation
CREATE TABLE employees (
  id INT PRIMARY KEY IDENTITY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) UNIQUE,
  hire_date DATE DEFAULT GETDATE(),
  salary DECIMAL(10,2) CHECK (salary > 0)
);

CREATE SEQUENCE emp_seq START WITH 1;
Common Data Types
  • INT, BIGINT: Integer values
  • VARCHAR(n): Variable string
  • DATE, DATETIME: Date and time
  • DATETIME2: Precise date/time
  • CHAR(n): Fixed-length string
  • DECIMAL(p,s): Exact numeric

Basic SQL Queries

Filtering Data
SELECT TOP 5 product_name, price
FROM products
WHERE price > 100 
  AND category = 'Electronics'
ORDER BY price DESC;
Sorting & Limiting
SELECT * FROM customers
ORDER BY last_name ASC, 
         first_name ASC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

Modifying Data (DML)

INSERT
INSERT INTO employees 
(name, email, salary)
VALUES 
('John Doe', 'john@example.com', 50000);
UPDATE
UPDATE employees
SET salary = salary * 1.1
WHERE department = 'Sales';
DELETE
DELETE FROM products
WHERE discontinued = 1;

Advanced Filtering

IN, BETWEEN, LIKE
SELECT * FROM products
WHERE category IN ('Electronics', 'Books')
  AND price BETWEEN 50 AND 200
  AND product_name LIKE '%Phone%';
NULL Handling
SELECT * FROM customers
WHERE phone IS NOT NULL;

UPDATE employees
SET manager_id = NULL
WHERE manager_id = 10;

Working with Multiple Tables

INNER JOIN
SELECT o.order_id, c.customer_name
FROM orders o
INNER JOIN customers c 
  ON o.customer_id = c.customer_id;
LEFT JOIN
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d
  ON e.dept_id = d.dept_id;
Self Join Example
SELECT e1.name AS employee, 
       e2.name AS manager
FROM employees e1
LEFT JOIN employees e2
  ON e1.manager_id = e2.employee_id;

Aggregation and Grouping

Aggregate Functions
SELECT 
  COUNT(*) AS total_products,
  AVG(price) AS avg_price,
  MIN(price) AS min_price,
  MAX(price) AS max_price,
  SUM(stock) AS total_stock
FROM products;
GROUP BY & HAVING
SELECT department_id, 
  COUNT(*) AS emp_count,
  AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5
ORDER BY avg_salary DESC;
Key Differences
  • WHERE filters before grouping
  • HAVING filters after grouping
  • Non-aggregated columns in SELECT must be in GROUP BY
  • Aggregate functions can't be used in WHERE

Subqueries

Single-Row Subquery
SELECT name, salary
FROM employees
WHERE salary > (
  SELECT AVG(salary)
  FROM employees
);
Multi-Row Subquery
SELECT product_name, price
FROM products
WHERE category_id IN (
  SELECT category_id
  FROM categories
  WHERE department = 'Electronics'
);
Correlated Subquery
SELECT e.name, e.salary, e.department_id
FROM employees e
WHERE salary > (
  SELECT AVG(salary)
  FROM employees
  WHERE department_id = e.department_id
);

Views and Indexes

Creating Views
CREATE OR ALTER VIEW high_paid_employees AS
SELECT id, name, salary, department
FROM employees
WHERE salary > 100000
WITH CHECK OPTION;

SELECT * FROM high_paid_employees;
Creating Indexes
CREATE INDEX idx_employee_name 
ON employees(name);

CREATE UNIQUE INDEX idx_customer_email
ON customers(email);

CREATE INDEX idx_order_dates
ON orders(order_date, shipped_date);
Index Best Practices
  • Index columns frequently used in WHERE, JOIN, ORDER BY
  • Avoid over-indexing (slows down INSERT/UPDATE)
  • Consider composite indexes for multi-column queries
  • Monitor index usage and remove unused indexes

Basic SQL Functions

String Functions
SELECT 
  first_name + ' ' + last_name AS full_name,
  UPPER(email) AS email_upper,
  SUBSTRING(phone, 1, 3) AS area_code,
  LEN(address) AS addr_length
FROM customers;
Date Functions
SELECT 
  GETDATE() AS current_datetime,
  CAST(order_date AS DATE) AS order_date_only,
  DATEDIFF(DAY, GETDATE(), due_date) AS days_remaining,
  DATEADD(MONTH, 12, hire_date) AS anniversary
FROM orders;
Math Functions
SELECT 
  ROUND(price * 1.1, 2) AS price_with_tax,
  ABS(discount) AS absolute_discount,
  quantity % 10 AS remainder,
  CEILING(weight) AS rounded_weight
FROM products;

Transactions and ACID

Transaction Control
BEGIN TRANSACTION;

UPDATE accounts 
SET balance = balance - 100
WHERE id = 123;

UPDATE accounts 
SET balance = balance + 100
WHERE id = 456;

COMMIT TRANSACTION;
-- or ROLLBACK TRANSACTION if error occurs
ACID Properties
  • Atomicity: All or nothing execution
  • Consistency: Valid state transitions
  • Isolation: Concurrent transactions don't interfere
  • Durability: Committed changes persist

Stored Procedures & Functions

Stored Procedure
CREATE OR ALTER PROCEDURE update_salary
  @emp_id INT,
  @increase_percent DECIMAL(5,2)
AS
BEGIN
  UPDATE employees
  SET salary = salary * (1 + @increase_percent/100)
  WHERE id = @emp_id;
  
  RETURN @@ROWCOUNT;
END;
GO

EXEC update_salary @emp_id = 101, @increase_percent = 10;
Scalar Function
CREATE OR ALTER FUNCTION get_employee_age(
  @emp_id INT
) RETURNS INT
AS
BEGIN
  DECLARE @age INT;
  
  SELECT @age = DATEDIFF(YEAR, birth_date, GETDATE())
  FROM employees
  WHERE id = @emp_id;
  
  RETURN @age;
END;
GO

SELECT name, dbo.get_employee_age(id) AS age
FROM employees;

Want to Practice SQL Server?

Try these concepts with real-world exercises

Start Practicing Now