SQL Cheatsheet: Clauses, Commands, Patterns
Keep this page open while you work. Every block here is the shortest correct form of a task you will do hundreds of times.
- Clause order â the sequence the parser enforces, and the mental order for writing
- Quick tables â filtering, joining, grouping, shaping, and window syntax side by side
- Command families â DDL, DML, DCL, and TCL with the exact statements you need
- Copy-ready patterns â upserts, top-N-per-group, running totals, and safe deletes Bookmark it; the goal is recall speed, not memorization for its own sake.
Prerequisites
- !Basic knowledge of SELECT, FROM, and WHERE
- !Access to any SQL engine to try the snippets
What You'll Learn
- 1Recall the legal clause order of a SELECT statement instantly
- 2Look up filtering, grouping, and window syntax without leaving the page
- 3Pick the right command family (DDL, DML, DCL, TCL) for a task
- 4Adapt copy-ready patterns such as upserts and top-N-per-group to your engine
Clause Order: Written versus Executed
SQL is read top to bottom by humans and executed in a different order by the engine. Knowing both explains why a column alias defined in SELECT cannot be used in WHERE, and why filtering happens before sorting.
| You write | The engine executes | What it does |
|---|---|---|
FROM / JOIN | 1 | Sources rows; builds the working set |
WHERE | 2 | Filters rows before grouping |
GROUP BY | 3 | Collapses rows into groups |
HAVING | 4 | Filters groups after aggregation |
SELECT | 5 | Evaluates expressions and aliases |
DISTINCT | 6 | Removes duplicate result rows |
ORDER BY | 7 | Sorts the result |
LIMIT / OFFSET | 8 | Truncates the sorted result |
To filter on an aggregate, use HAVING or a subquery. To filter on an alias you just computed, wrap the query in a CTE and filter in the outer query â the clearest portable fix.
Filtering and Pattern Matching
| Task | Syntax | Notes |
|---|---|---|
| Range | WHERE amount BETWEEN 10 AND 50 | Inclusive on both ends |
| Membership | WHERE status IN ('new', 'open') | Watch NULLs with NOT IN |
| Null check | WHERE deleted_at IS NULL | Never = NULL |
| Pattern | WHERE name LIKE 'Acme%' | % any sequence, _ one character |
| Case-insensitive | WHERE name ILIKE '%acme%' | PostgreSQL; use LOWER() elsewhere |
| Regex | WHERE name ~* '^acme' | PostgreSQL ~ / ~*; REGEXP in MySQL |
| Any of two conditions | WHERE a = 1 OR b = 2 | Prefer OR of indexed terms over IN on functions |
| All of two conditions | WHERE a = 1 AND b = 2 | Evaluate selective conditions the planner can reorder |
| Not equal | WHERE status <> 'done' | NULL rows drop out; add OR status IS NULL if needed |
| Exists related row | WHERE EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id) | Usually better than IN for correlated checks |
Join Syntax at a Glance
| Join | Syntax | Keeps |
|---|---|---|
| Inner | FROM a INNER JOIN b ON a.id = b.a_id | Only matching pairs |
| Left | FROM a LEFT JOIN b ON a.id = b.a_id | All of a, matches from b |
| Full | FROM a FULL OUTER JOIN b ON a.id = b.a_id | All rows from both sides |
| Self | FROM employees e JOIN employees m ON e.manager_id = m.id | Hierarchical relationships |
| Cross | FROM a CROSS JOIN b | Every combination â always add a filter or a purpose |
| Anti | FROM a LEFT JOIN b ON ... WHERE b.id IS NULL | a rows with no match |
| Semi | WHERE EXISTS (SELECT 1 FROM b WHERE ...) | a rows with any match, no duplication |
A quick sanity check before aggregating a join: compare COUNT(*) to COUNT(DISTINCT a.id). If they differ, the join fans out and your sums are inflated.
Grouping, Windowing, and Shaping
-- One query, many cheatsheet staples: filter, group, rank, and shape
WITH monthly_sales AS (
SELECT
c.region,
c.customer_id,
DATE_TRUNC('month', o.order_date) AS month,
SUM(o.total) AS revenue
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_date >= DATE '2024-01-01'
AND o.status <> 'cancelled'
GROUP BY c.region, c.customer_id, DATE_TRUNC('month', o.order_date)
),
ranked AS (
SELECT
region,
month,
customer_id,
revenue,
ROW_NUMBER() OVER (PARTITION BY region, month ORDER BY revenue DESC) AS rn,
SUM(revenue) OVER (PARTITION BY region ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rev_3mo_trailing
FROM monthly_sales
)
SELECT
region,
month,
customer_id,
revenue,
rev_3mo_trailing
FROM ranked
WHERE rn <= 5 -- top 5 customers per region per month
ORDER BY region, month, revenue DESC;
| Task | Pattern |
|---|---|
| Aggregate by group | GROUP BY cols with HAVING SUM(x) > n |
| Running total | SUM(x) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) |
| Moving average | AVG(x) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) |
| Rank within group | ROW_NUMBER() / RANK() / DENSE_RANK() OVER (PARTITION BY g ORDER BY v DESC) |
| Top N per group | Filter ROW_NUMBER() = 1 in a subquery or CTE |
| Period comparison | LAG(x) OVER (ORDER BY month) then x - LAG(x) |
| Percent of total | 100.0 * x / SUM(x) OVER () |
| Gap-and-island | Compare ROW_NUMBER() over two orderings to form island keys |
DDL, DML, DCL, and TCL Command Reference
| Family | Statements | Typical use |
|---|---|---|
| DDL | CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX, CREATE VIEW | Shape the schema |
| DML | INSERT, UPDATE, DELETE, MERGE | Change rows |
| DCL | GRANT, REVOKE | Control access |
| TCL | BEGIN, COMMIT, ROLLBACK, SAVEPOINT | Group changes atomically |
-- Copy-ready DDL and DML patterns
-- Create a table with sensible keys and constraints
CREATE TABLE order_status_history (
history_id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders (order_id),
old_status TEXT,
new_status TEXT NOT NULL,
changed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_osh_order_time ON order_status_history (order_id, changed_at DESC);
-- Insert or update (upsert) on a unique key â PostgreSQL form
INSERT INTO order_status_history (order_id, old_status, new_status)
VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING;
-- MySQL equivalent of an upsert
-- INSERT INTO order_status_history (order_id, old_status, new_status)
-- VALUES (?, ?, ?)
-- ON DUPLICATE KEY UPDATE new_status = VALUES(new_status);
-- Transactional multi-step change with explicit boundaries
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;
String, Date, and Null Utilities
| Task | PostgreSQL | MySQL |
|---|---|---|
| Current timestamp | now() | NOW() |
| Date truncation | DATE_TRUNC('month', d) | DATE_FORMAT(d, '%Y-%m-01') |
| Date difference in days | d2 - d1 (interval) | DATEDIFF(d2, d1) |
| Concatenate | a || ' ' || b | CONCAT(a, ' ', b) |
| Split string | STRING_TO_ARRAY(s, ',') | â (8.0+: JSON_TABLE) |
| Replace null | COALESCE(x, 0) | IFNULL(x, 0) |
| Conditional | CASE WHEN x > 0 THEN 'pos' ELSE 'neg' END | Same |
| Cast | CAST(x AS NUMERIC(10,2)) | CAST(x AS DECIMAL(10,2)) |
Safe Delete and Update Recipes
Never modify rows without a verifiable scope. The reliable recipe: select the target rows by primary key inside a transaction, inspect the count, then apply the change.
BEGIN;
-- 1. Identify the rows you intend to touch
SELECT o.order_id, o.status, o.total
FROM orders o
WHERE o.status = 'cancelled'
AND o.order_date < DATE '2023-01-01';
-- 2. Delete via the same predicate, optionally scoped by keys from step 1
DELETE FROM orders o
WHERE o.status = 'cancelled'
AND o.order_date < DATE '2023-01-01';
-- 3. Confirm affected-row count matches expectation, then:
COMMIT;
-- If anything looks off: ROLLBACK;
For incremental loads, prefer MERGE (where supported) or INSERT ... ON CONFLICT over delete-then-insert; they avoid windows where the table is incomplete and play better with replicas.
Session Settings Worth Memorizing
Session-level configuration changes behavior for your connection only, which makes them ideal for one-off investigations without risking other users. Learn the handful you will actually reach for.
| Setting | Engines | What it is for |
|---|---|---|
SET LOCAL work_mem = '64MB' | PostgreSQL | Raise sort/hash memory for one transaction |
SET search_path = core, public | PostgreSQL | Control unqualified name resolution |
SET statement_timeout = '5s' | PostgreSQL | Kill runaway queries during testing |
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED | Both | Choose concurrency semantics explicitly |
EXPLAIN ANALYZE inside a transaction with rollback | Both | Measure write statements safely |
Treat these as diagnostic tools, not permanent fixes: a session setting that saves a query in your laptop client tells you what configuration the server actually needs, which belongs in the server's config files and change review process. Pair every investigation setting with a note in your findings so the durable fix is not forgotten once the query finally returns.
Common Mistakes
Using WHERE on an aggregate instead of HAVING
Fix: Filter aggregates with HAVING, or compute them in a CTE and filter in the outer query
Assuming MySQL supports ILIKE, STRING_TO_ARRAY, or :: casts
Fix: Check the dialect table above and keep a per-engine variant of your snippets
Running unscoped UPDATE or DELETE statements
Fix: SELECT first inside a transaction, match on primary keys, verify counts, then commit
Forgetting that NOT IN drops everything when the list contains NULL
Fix: Use NOT EXISTS or NOT IN over a subquery that filters NULLs out
Best Practices
- Keep this page or a printed copy within reach while onboarding to a new stack
- Store engine-specific variants of upsert and date snippets in your team wiki
- Validate any copy-pasted snippet against a small test table before production use
- Prefer CTEs over inline aliases you cannot reference in WHERE
Key Takeaways
- Write FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY â the engine executes in roughly that order
- Joins plus aggregation are the most common source of inflated metrics; verify cardinality
- Window functions replace many self-joins for ranking, running totals, and period comparisons
- DDL, DML, DCL, and TCL are four command families with distinct blast radii
- Scope every write statement and wrap it in a transaction you can roll back