SQL Cheatsheet
A complete SQL cheatsheet from beginner to advanced — SELECT, JOINs, aggregations, subqueries, CTEs, window functions, transactions, indexes, and modern SQL patterns for PostgreSQL, MySQL, SQLite and more.
SQL (Structured Query Language) is the standard language for managing and querying relational databases. This cheatsheet covers beginner fundamentals through advanced analytical and modern SQL features. Examples work in most major dialects (PostgreSQL, MySQL, SQLite, SQL Server) with notes where they differ.
SELECT column1, column2FROM table_nameWHERE conditionGROUP BY column1HAVING aggregate_conditionORDER BY column1 ASC|DESCLIMIT 10 OFFSET 20;SELECT * FROM users; -- all columnsSELECT id, name, email FROM users; -- specific columnsSELECT DISTINCT country FROM users; -- unique valuesSELECT name AS full_name FROM users; -- aliasSELECT name full_name FROM users; -- alias (AS optional)SELECT * FROM users WHERE age > 18;SELECT * FROM users WHERE age BETWEEN 18 AND 30;SELECT * FROM users WHERE country IN ('BD', 'IN', 'PK');SELECT * FROM users WHERE name LIKE 'A%'; -- starts with ASELECT * FROM users WHERE name LIKE '%son'; -- ends with sonSELECT * FROM users WHERE name LIKE '%ali%'; -- contains aliSELECT * FROM users WHERE name ILIKE 'a%'; -- case-insensitive (PostgreSQL)SELECT * FROM users WHERE email IS NULL;SELECT * FROM users WHERE email IS NOT NULL;
-- Logical operatorsSELECT * FROM usersWHERE age >= 18 AND country = 'BD' OR (status = 'active' AND role = 'admin');
SELECT * FROM users WHERE NOT status = 'banned';NULL handling:
-- Never use = NULL or != NULLWHERE col IS NULLWHERE col IS NOT NULLCOALESCE(col, 'default') -- return first non-nullNULLIF(a, b) -- return NULL if a = bSELECT * FROM products ORDER BY price ASC;SELECT * FROM products ORDER BY price DESC, name ASC;SELECT * FROM products ORDER BY price NULLS LAST; -- PostgreSQL
SELECT * FROM products LIMIT 10; -- first 10SELECT * FROM products LIMIT 10 OFFSET 20; -- paginationSELECT * FROM products OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; -- SQL standardSELECT COUNT(*) FROM users;SELECT COUNT(email) FROM users; -- ignores NULLsSELECT COUNT(DISTINCT country) FROM users;
SELECT SUM(price), AVG(price), MIN(price), MAX(price)FROM orders;
SELECT country, COUNT(*) AS user_countFROM usersGROUP BY countryORDER BY user_count DESC;
SELECT country, city, COUNT(*)FROM usersGROUP BY country, city;
-- Filter groupsSELECT country, COUNT(*) AS cntFROM usersGROUP BY countryHAVING COUNT(*) > 100;-- INNER JOIN (only matching rows)SELECT u.name, o.totalFROM users uINNER JOIN orders o ON u.id = o.user_id;
-- LEFT JOIN (all from left + matches from right)SELECT u.name, o.totalFROM users uLEFT JOIN orders o ON u.id = o.user_id;
-- RIGHT JOINSELECT u.name, o.totalFROM users uRIGHT JOIN orders o ON u.id = o.user_id;
-- FULL OUTER JOIN (PostgreSQL, SQL Server)SELECT u.name, o.totalFROM users uFULL OUTER JOIN orders o ON u.id = o.user_id;
-- CROSS JOIN (Cartesian product)SELECT * FROM colors CROSS JOIN sizes;
-- Self joinSELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees m ON e.manager_id = m.id;
-- Multiple joinsSELECT u.name, o.id AS order_id, p.name AS productFROM users uJOIN orders o ON u.id = o.user_idJOIN order_items oi ON o.id = oi.order_idJOIN products p ON oi.product_id = p.id;-- Subquery in WHERESELECT * FROM productsWHERE price > (SELECT AVG(price) FROM products);
SELECT * FROM usersWHERE id IN (SELECT user_id FROM orders WHERE total > 1000);
SELECT * FROM users uWHERE EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id);
-- Subquery in FROM (derived table)SELECT country, avg_ageFROM ( SELECT country, AVG(age) AS avg_age FROM users GROUP BY country) tWHERE avg_age > 30;
-- Subquery in SELECTSELECT name, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_countFROM users u;-- Basic CTEWITH active_users AS ( SELECT * FROM users WHERE status = 'active')SELECT * FROM active_users WHERE country = 'BD';
-- Multiple CTEsWITH active_users AS ( SELECT id, name FROM users WHERE status = 'active' ), recent_orders AS ( SELECT * FROM orders WHERE created_at > CURRENT_DATE - INTERVAL '30 days' )SELECT u.name, COUNT(o.id) AS ordersFROM active_users uJOIN recent_orders o ON u.id = o.user_idGROUP BY u.name;
-- Recursive CTE (hierarchical data)WITH RECURSIVE category_tree AS ( SELECT id, name, parent_id, 1 AS level FROM categories WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, c.parent_id, ct.level + 1 FROM categories c JOIN category_tree ct ON c.parent_id = ct.id)SELECT * FROM category_tree ORDER BY level, name;Window functions compute values across a set of rows related to the current row without collapsing groups.
SELECT name, department, salary, AVG(salary) OVER (PARTITION BY department) AS dept_avg, salary - AVG(salary) OVER (PARTITION BY department) AS diff_from_avg, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_in_dept, ROW_NUMBER() OVER (ORDER BY salary DESC) AS overall_rank, LAG(salary) OVER (PARTITION BY department ORDER BY hire_date) AS prev_salary, LEAD(salary) OVER (PARTITION BY department ORDER BY hire_date) AS next_salary, SUM(salary) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_totalFROM employees;Common window functions:
- Ranking:
ROW_NUMBER(),RANK(),DENSE_RANK(),NTILE(n) - Value:
LAG(),LEAD(),FIRST_VALUE(),LAST_VALUE(),NTH_VALUE() - Aggregate:
SUM(),AVG(),COUNT(),MIN(),MAX()(with OVER)
SELECT name, CASE WHEN age < 18 THEN 'minor' WHEN age BETWEEN 18 AND 64 THEN 'adult' ELSE 'senior' END AS age_groupFROM users;
-- Simple CASESELECT CASE status WHEN 'active' THEN 'Active User' WHEN 'pending' THEN 'Waiting' ELSE 'Other' END AS status_labelFROM users;
-- In aggregationSELECT COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count, COUNT(CASE WHEN status = 'banned' THEN 1 END) AS banned_countFROM users;INSERT INTO users (name, email, age)VALUES ('Rahim', 'rahim@example.com', 28);
INSERT INTO users (name, email) VALUES ('Karim', 'karim@example.com'), ('Ayesha', 'ayesha@example.com');
-- Insert from SELECTINSERT INTO archived_users (id, name, email)SELECT id, name, email FROM users WHERE last_login < '2024-01-01';
-- Upsert (PostgreSQL)INSERT INTO users (email, name)VALUES ('rahim@example.com', 'Rahim')ON CONFLICT (email) DO UPDATESET name = EXCLUDED.name;
-- Upsert (MySQL)INSERT INTO users (email, name)VALUES ('rahim@example.com', 'Rahim')ON DUPLICATE KEY UPDATE name = VALUES(name);UPDATE usersSET name = 'Rahim Ahmed', age = 29WHERE id = 1;
UPDATE usersSET status = 'inactive'WHERE last_login < CURRENT_DATE - INTERVAL '1 year';
-- Update with JOIN (PostgreSQL / SQL Server style)UPDATE users uSET status = 'vip'FROM orders oWHERE u.id = o.user_id AND o.total > 10000;DELETE FROM users WHERE id = 1;DELETE FROM users WHERE status = 'banned' AND last_login IS NULL;
-- Delete with JOIN / subqueryDELETE FROM usersWHERE id IN (SELECT user_id FROM spam_accounts);-- UNION (removes duplicates)SELECT name FROM customersUNIONSELECT name FROM suppliers;
-- UNION ALL (keeps duplicates)SELECT name FROM customersUNION ALLSELECT name FROM suppliers;
-- INTERSECT (rows common to both)SELECT name FROM customersINTERSECTSELECT name FROM suppliers;
-- EXCEPT / MINUS (rows in first but not second)SELECT name FROM customersEXCEPTSELECT name FROM suppliers;-- Primary Key & Foreign Key (usually defined in CREATE TABLE)CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, total NUMERIC(12,2) CHECK (total >= 0), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
-- IndexesCREATE INDEX idx_users_email ON users(email);CREATE UNIQUE INDEX idx_users_email_unique ON users(email);CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
-- Partial index (PostgreSQL)CREATE INDEX idx_active_users ON users(email) WHERE status = 'active';BEGIN; -- or START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- If everything is fineCOMMIT;
-- If something went wrongROLLBACK;
-- SavepointsBEGIN;UPDATE ...;SAVEPOINT my_save;UPDATE ...;ROLLBACK TO my_save;COMMIT;CREATE VIEW active_users ASSELECT id, name, emailFROM usersWHERE status = 'active';
SELECT * FROM active_users;
-- Materialized view (PostgreSQL)CREATE MATERIALIZED VIEW sales_summary ASSELECT date_trunc('month', created_at) AS month, SUM(total) AS revenueFROM ordersGROUP BY 1;
REFRESH MATERIALIZED VIEW sales_summary;-- StringCONCAT(a, b) / a || bLENGTH(str) / CHAR_LENGTH(str)UPPER(str) / LOWER(str)TRIM(str) / LTRIM / RTRIMSUBSTRING(str FROM 1 FOR 3)REPLACE(str, 'old', 'new')SPLIT_PART(str, ',', 1) -- PostgreSQL
-- NumericROUND(n, 2)FLOOR(n) / CEIL(n)ABS(n)MOD(a, b)
-- Date / TimeCURRENT_DATE / CURRENT_TIMESTAMP / NOW()DATE_TRUNC('month', ts) -- PostgreSQLEXTRACT(YEAR FROM ts)ts + INTERVAL '7 days'AGE(end_ts, start_ts)
-- ConditionalCOALESCE(a, b, c)NULLIF(a, b)GREATEST(a, b, c)LEAST(a, b, c)SELECT * FROM productsWHERE (created_at, id) < ('2025-01-01 12:00:00', 12345)ORDER BY created_at DESC, id DESCLIMIT 20;SELECT DISTINCT ON (email) *FROM usersORDER BY email, created_at DESC; -- PostgreSQLSELECT date, COUNT(*) FILTER (WHERE status = 'completed') AS completed, COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelledFROM ordersGROUP BY date;SELECT department, COUNT(CASE WHEN gender = 'M' THEN 1 END) AS male_count, COUNT(CASE WHEN gender = 'F' THEN 1 END) AS female_countFROM employeesGROUP BY department;- Select only needed columns — avoid
SELECT *in production. - Filter early — use WHERE before joining large tables when possible.
- Index wisely — index columns used in WHERE, JOIN, and ORDER BY.
- Prefer CTEs for readability over deeply nested subqueries.
- Use transactions for multi-step writes that must succeed or fail together.
- Handle NULLs explicitly — they propagate in unexpected ways.
- Avoid OFFSET for deep pagination — use keyset pagination instead.
- Write deterministic queries — be careful with floating-point and unordered results.
- Use EXPLAIN / EXPLAIN ANALYZE to understand query plans.
- Keep business logic consistent — decide whether logic lives in SQL or application code.
-- Basic querySELECT col FROM table WHERE condition ORDER BY col LIMIT n;
-- JoinSELECT ... FROM a JOIN b ON a.id = b.a_id;
-- AggregationSELECT col, COUNT(*) FROM table GROUP BY col HAVING COUNT(*) > 1;
-- CTEWITH cte AS (SELECT ...) SELECT * FROM cte;
-- WindowSELECT ..., ROW_NUMBER() OVER (PARTITION BY x ORDER BY y) FROM table;
-- Upsert (PostgreSQL)INSERT ... ON CONFLICT (key) DO UPDATE SET ...;
-- TransactionBEGIN; ...; COMMIT; -- or ROLLBACK;- PostgreSQL Docs: https://www.postgresql.org/docs/
- MySQL Docs: https://dev.mysql.com/doc/
- SQLite Docs: https://www.sqlite.org/docs.html
- Mode SQL Tutorial: https://mode.com/sql-tutorial/
- Use The Index, Luke: https://use-the-index-luke.com/
- SQL Style Guide: https://www.sqlstyle.guide/
This cheatsheet focuses on standard and widely supported SQL. Always check your specific database dialect (PostgreSQL, MySQL, SQLite, SQL Server, etc.) for exact function names and feature support.
Frequently asked questions
What is the difference between WHERE and HAVING?
WHERE filters rows before grouping. HAVING filters groups after aggregation. Use WHERE for individual rows and HAVING for aggregated results.
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only matching rows from both tables. LEFT JOIN returns all rows from the left table and matching rows from the right (NULLs when no match).
What is a CTE?
A Common Table Expression (WITH clause) defines a temporary named result set that exists only for the duration of the query. It improves readability and enables recursion.
What are window functions?
Window functions perform calculations across a set of rows related to the current row without collapsing them into a single output row (unlike GROUP BY).
How do I handle NULLs safely?
Use IS NULL / IS NOT NULL for checks. Use COALESCE or IFNULL to provide defaults. Remember that NULL = NULL is unknown (not true).