79 entries · 8 sections
SQL Cheat Sheet
The SQL you write most days: selecting and filtering, joins, grouping, common table expressions, window functions, and the statements that change data or schema. Dialect differences between PostgreSQL, MySQL, SQLite and SQL Server are noted where they actually bite.
Selecting rows
| Syntax | What it does |
|---|---|
SELECT * FROM users; | Every column of every row. Fine while exploring, wasteful in application code. |
SELECT id, email FROM users; | Only the columns you need — less I/O and a stable contract. |
SELECT DISTINCT country FROM users; | The unique values of a column. |
SELECT name AS full_name FROM users; | Rename a column in the result set. |
SELECT COUNT(*) FROM users; | How many rows there are. |
SELECT * FROM users LIMIT 10; | The first ten rows. SQL Server uses SELECT TOP 10; standard SQL uses FETCH FIRST 10 ROWS ONLY. |
SELECT * FROM users LIMIT 10 OFFSET 20; | Skip twenty rows, then take ten — page three. |
SELECT * FROM users ORDER BY created_at DESC; | Newest first. Without ORDER BY, row order is not guaranteed at all. |
SELECT * FROM users ORDER BY country, name; | Sort by one key, then break ties with another. |
SELECT * FROM users ORDER BY score DESC NULLS LAST; | Control where NULLs land (PostgreSQL and Oracle). |
Filtering
| Syntax | What it does |
|---|---|
WHERE age > 18 | Comparison operators: = <> < <= > >=. Some dialects also accept != for <>. |
WHERE a AND b / WHERE a OR b / WHERE NOT a | Combine conditions. Parenthesise whenever you mix AND with OR. |
WHERE country IN ('IN', 'US') | Match any value in a list. |
WHERE age BETWEEN 18 AND 30 | An inclusive range on both ends. |
WHERE email LIKE '%@gmail.com' | Pattern match: % is any run of characters, _ is exactly one. |
WHERE email ILIKE '%GMAIL%' | Case-insensitive LIKE (PostgreSQL). Elsewhere use LOWER(email) LIKE ... |
WHERE deleted_at IS NULL | The only way to test for NULL. Anything = NULL is never true. |
WHERE COALESCE(nickname, name) = 'Ada' | Use the first value that is not NULL. |
WHERE id IN (SELECT user_id FROM orders) | Filter by the result of another query. |
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id) | True when the subquery returns any row. Usually faster than IN on large sets. |
Joins
| Syntax | What it does |
|---|---|
INNER JOIN orders o ON o.user_id = u.id | Only the rows that match on both sides. A bare JOIN means INNER JOIN. |
LEFT JOIN orders o ON o.user_id = u.id | Every left row; unmatched right-hand columns come back NULL. |
RIGHT JOIN orders o ON o.user_id = u.id | The mirror image of LEFT JOIN. Rare, because you can usually swap the tables. |
FULL OUTER JOIN a ON ... | Everything from both sides, NULL where there is no partner. MySQL has no FULL OUTER JOIN; SQLite added it in 3.39 (2022). |
CROSS JOIN sizes | Every combination of both tables — the Cartesian product. |
JOIN users m ON m.id = u.manager_id | A self-join: the same table again under a second alias. |
LEFT JOIN o ON ... WHERE o.id IS NULL | The anti-join: left rows that have no match at all. |
USING (user_id) | Shorthand for ON a.user_id = b.user_id when both columns share a name. |
LATERAL / CROSS APPLY | Let a joined subquery reference columns from the row on its left. LATERAL in PostgreSQL, CROSS APPLY in SQL Server. |
Grouping and aggregates
| Syntax | What it does |
|---|---|
COUNT(*) vs COUNT(col) | All rows, versus only the rows where that column is not NULL. |
SUM(amount), AVG(amount) | Total and mean. Both ignore NULLs. |
MIN(col), MAX(col) | The smallest and largest values. |
GROUP BY country | Collapse the rows into one per country. |
GROUP BY country HAVING COUNT(*) > 10 | Filter the groups. WHERE filters rows before grouping, HAVING filters groups after. |
COUNT(DISTINCT user_id) | Count unique users rather than unique rows. |
ROUND(AVG(amount), 2) | Round an aggregate to two decimal places. |
STRING_AGG(name, ', ') | Concatenate a group into one string. MySQL and SQLite call it GROUP_CONCAT. |
FILTER (WHERE status = 'paid') | Aggregate only a subset — COUNT(*) FILTER (WHERE ...) in PostgreSQL and SQLite. |
SELECT country, COUNT(*) FROM users GROUP BY country ORDER BY 2 DESC; | Top countries by user count. ORDER BY 2 sorts by the second output column. |
CTEs, subqueries and set operations
| Syntax | What it does |
|---|---|
WITH recent AS (SELECT ...) SELECT * FROM recent; | Name a subquery and reuse it. Far more readable than nesting. |
WITH a AS (...), b AS (...) SELECT ... | Chain several CTEs in one statement; later ones can refer to earlier ones. |
WITH RECURSIVE tree AS (...) SELECT * FROM tree; | Walk a hierarchy such as a category or org tree. |
SELECT ... UNION SELECT ... | Combine two result sets and remove duplicate rows. |
UNION ALL | Combine without deduplicating. Faster — use it unless you genuinely need the dedupe. |
INTERSECT | Rows produced by both queries. |
EXCEPT | Rows in the first query but not the second. Oracle spells it MINUS. |
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) | A correlated scalar subquery: one value computed per outer row. |
Window functions
| Syntax | What it does |
|---|---|
ROW_NUMBER() OVER (ORDER BY score DESC) | 1, 2, 3 with no ties, in the given order. |
RANK() OVER (ORDER BY score DESC) | Ties share a rank and the following rank is skipped: 1, 1, 3. |
DENSE_RANK() OVER (ORDER BY score DESC) | Ties share a rank and nothing is skipped: 1, 1, 2. |
SUM(amount) OVER (PARTITION BY user_id) | A per-user total attached to every row, without collapsing the rows. |
SUM(amount) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) | A running total. |
AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) | A seven-row moving average. |
LAG(amount) OVER (ORDER BY d) | The previous row's value — how you compute deltas. |
LEAD(amount) OVER (ORDER BY d) | The next row's value. |
NTILE(4) OVER (ORDER BY score) | Split the rows into four equal buckets — quartiles. |
FIRST_VALUE(x) OVER (PARTITION BY g ORDER BY d) | The first value inside each partition. |
Changing data
| Syntax | What it does |
|---|---|
INSERT INTO users (name, email) VALUES ('Ada', 'a@b.c'); | Insert one row. |
INSERT INTO users (name) VALUES ('A'), ('B'); | Insert several rows in one statement. |
INSERT INTO archive SELECT * FROM users WHERE ...; | Insert the result of a query. |
UPDATE users SET plan = 'pro' WHERE id = 7; | Update the matching rows. Without WHERE it updates every row in the table. |
UPDATE users SET n = n + 1 WHERE id = 7; | Update relative to the current value. |
DELETE FROM users WHERE id = 7; | Delete the matching rows. |
TRUNCATE TABLE logs; | Empty a table quickly. It skips row triggers and, in some engines, cannot be rolled back. |
INSERT ... ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name; | Upsert in PostgreSQL and SQLite. MySQL uses ON DUPLICATE KEY UPDATE. |
RETURNING id | Get the affected rows back from an INSERT, UPDATE or DELETE (PostgreSQL and SQLite). |
BEGIN; ... COMMIT; / ROLLBACK; | Wrap several statements in one transaction so they succeed or fail together. |
Defining tables and tuning
| Syntax | What it does |
|---|---|
CREATE TABLE t (id INT PRIMARY KEY, name TEXT NOT NULL); | Create a table with a primary key and a required column. |
CREATE TABLE IF NOT EXISTS t (...); | Create it only when it is missing. |
ALTER TABLE t ADD COLUMN age INT; | Add a column. |
ALTER TABLE t DROP COLUMN age; | Remove a column and its data. |
ALTER TABLE t RENAME COLUMN a TO b; | Rename a column. |
DROP TABLE IF EXISTS t; | Delete a table and everything in it. |
CREATE INDEX idx_users_email ON users(email); | Index a column you filter, join or sort on. |
CREATE UNIQUE INDEX ... ON users(email); | An index that also enforces uniqueness. |
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE | Link two tables and remove the children with the parent. |
DEFAULT CURRENT_TIMESTAMP | A column default — the usual way to fill created_at. |
CHECK (amount >= 0) | Constrain the values a column is allowed to hold. |
EXPLAIN ANALYZE SELECT ... | Show the query plan and the real timings. The first step of every optimisation. |
Worth knowing
- WHERE filters rows before grouping and HAVING filters groups afterwards, which is why HAVING COUNT(*) > 10 works and WHERE COUNT(*) > 10 is a syntax error. If a condition does not involve an aggregate, put it in WHERE — the database then has fewer rows to group.
- An index helps a query only if the column appears in a way the index can use. WHERE LOWER(email) = ... cannot use a plain index on email; you need an expression index or a citext column. Wrapping an indexed column in a function is the most common reason a query is unexpectedly slow.
- Always run a destructive UPDATE or DELETE as a SELECT first with the same WHERE clause, then wrap the real statement in BEGIN so you can inspect the row count before COMMIT. A missing WHERE clause is the classic production incident, and it takes ten seconds to avoid.
Try a snippet instead of reading about it
Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.
Open the editorSQL — common questions
- What is the difference between INNER JOIN and LEFT JOIN?
- INNER JOIN returns only the rows that have a match on both sides, so unmatched rows disappear from the result. LEFT JOIN returns every row from the left table and fills the right-hand columns with NULL where there is no match — which is how you count users including those with zero orders.
- When should I use a CTE instead of a subquery?
- Use a CTE when the same subquery is needed more than once, when the query is deep enough that naming the steps makes it readable, or when you need recursion. Modern PostgreSQL inlines CTEs by default so there is normally no performance penalty; add MATERIALIZED or NOT MATERIALIZED when you want to control that.
- Why does WHERE column = NULL return nothing?
- Because NULL means unknown, and any comparison with unknown is itself unknown rather than true. Use IS NULL and IS NOT NULL instead. The same trap applies to NOT IN with a list that contains a NULL — it returns no rows at all.
- What is the difference between DELETE, TRUNCATE and DROP?
- DELETE removes rows one at a time, honours WHERE, fires triggers and can be rolled back. TRUNCATE empties the whole table quickly by deallocating storage, skips row triggers and often resets identity counters. DROP removes the table definition itself along with all its data and indexes.