SQL Cheat Sheet
Queries · Joins · Windows
SELECT/WHERE/JOINs, window functions, CTEs, indexes, common patterns and an interview-prep query bank — all on one card.
PDF quick reference
SQLCheat sheet
- Sections
- 6
- Snippets
- 12
- Pages
- 2
01
SELECT basics
SELECT name, salaryFROM employeesWHERE department = 'Engineering'ORDER BY salary DESCLIMIT 10;
SELECT department,AVG(salary) AS avg_salary,COUNT(*) AS headcountFROM employeesGROUP BY departmentHAVING COUNT(*) >= 5;
02
JOINs
SELECT o.id, c.nameFROM orders oINNER JOIN customers c ON o.customer_id = c.id;
SELECT c.nameFROM customers cLEFT JOIN orders o ON o.customer_id = c.idWHERE o.id IS NULL; -- customers with no orders
03
CTEs
WITH top_products AS (SELECT product_id, SUM(quantity) AS qtyFROM order_itemsGROUP BY product_idORDER BY qty DESCLIMIT 10)SELECT * FROM top_products;
04
Window functions
SELECT order_date,amount,SUM(amount) OVER (ORDER BY order_date) AS running_totalFROM orders;
SELECT name, salary,RANK() OVER (PARTITION BY departmentORDER BY salary DESC) AS rkFROM employees;
SELECT user_id, login_at,LAG(login_at) OVER (PARTITION BY user_idORDER BY login_at) AS prev_loginFROM logins;
05
Indexes & performance
CREATE INDEX idx_orders_userON orders(user_id);-- queries that filter on user_id will use it automatically
EXPLAIN ANALYZESELECT * FROM ordersWHERE user_id = 42;
06
Interview classics
SELECT MAX(salary) AS second_highestFROM employeesWHERE salary < (SELECT MAX(salary) FROM employees);
SELECT email, COUNT(*) cFROM usersGROUP BY emailHAVING COUNT(*) > 1;
