SQL Cheat Sheet — Queries, Joins, Aggregations & Indexing

Comprehensive SQL reference for SELECT queries, INNER/LEFT/FULL JOINs, GROUP BY, HAVING, subqueries, and table constraints.

Essential SELECT & Filters

SELECT DISTINCT country FROM users;

Return only unique, deduplicated values for country

SELECT * FROM orders WHERE status = "shipped" ORDER BY created_at DESC LIMIT 50;

Filter, sort newest first, and limit row count

SELECT * FROM products WHERE price BETWEEN 10 AND 50 AND category IN ("Books", "Games");

Filter range and multiple target options

SELECT * FROM users WHERE email LIKE "%@gmail.com";

Wildcard pattern matching (% matches zero or more characters)

JOIN Operations Explained

SELECT u.name, o.total FROM users u INNER JOIN orders o ON u.id = o.user_id;

INNER JOIN: Returns rows that have matching values in both tables

SELECT u.name, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id;

LEFT JOIN: Returns all users, plus orders if any (null if no orders)

SELECT * FROM table_a FULL OUTER JOIN table_b ON table_a.id = table_b.id;

FULL OUTER JOIN: Returns all records when there is a match in either left or right

Aggregations & Grouping

SELECT category, COUNT(*), AVG(price) FROM products GROUP BY category;

Group rows and calculate count and average per category

SELECT department, SUM(salary) FROM employees GROUP BY department HAVING SUM(salary) > 100000;

HAVING filters aggregated grouped results (unlike WHERE which filters rows before grouping)

Indexes & Performance

CREATE INDEX idx_users_email ON users(email);

Create a B-tree index on email column to make lookup queries O(log N)

EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 42;

Inspect query execution plan, index usage, and actual execution time