SQL Cheatsheet - Common Query Syntax & Examples
The most-used, easiest-to-forget SQL syntax in one place: queries, joins, aggregation, window functions and transactions, with copy-ready examples.
Back to DatabasesBasic Query 6
SELECT * FROM usersSelect all columns
SELECT name, age FROM usersSelect specific columns
SELECT * FROM users WHERE age > 18Filter with condition
SELECT DISTINCT city FROM usersRemove duplicates
SELECT * FROM users LIMIT 10 OFFSET 20Pagination (skip 20, take 10)
SELECT * FROM users ORDER BY age DESCSort descending
Filtering & Logic 6
WHERE name LIKE 'A%'Prefix match
WHERE name LIKE '%son'Suffix match
WHERE age BETWEEN 18 AND 30Range
WHERE id IN (1, 2, 3)Set membership
WHERE a IS NULLNull check
WHERE a AND b OR cLogic (AND precedes OR)
Aggregation & Grouping 5
SELECT COUNT(*) FROM usersCount
SELECT AVG(age) FROM usersAverage
SELECT city, COUNT(*) FROM users GROUP BY cityGroup by city
HAVING COUNT(*) > 5Filter after grouping (on aggregates)
SELECT MAX(age), MIN(age) FROM usersMax / min
JOIN 5
FROM a JOIN b ON a.id = b.a_idInner join
FROM a LEFT JOIN b ON a.id = b.a_idLeft join (keep all of a)
FROM a RIGHT JOIN b ON a.id = b.a_idRight join
FROM a CROSS JOIN bCartesian product
SELECT * FROM a NATURAL JOIN bAuto-join on same-named columns
Window Functions 4
ROW_NUMBER() OVER (ORDER BY age)Row number
RANK() OVER (PARTITION BY city ORDER BY age)Rank (gaps on ties)
SUM(amount) OVER (PARTITION BY user_id)Partitioned running total
LAG(price) OVER (ORDER BY date)Previous row value
DML & Transactions 5
INSERT INTO t (a, b) VALUES (1, 'x')Insert
UPDATE t SET a = 2 WHERE id = 1Update
DELETE FROM t WHERE id = 1Delete
BEGIN; ... COMMIT;Commit transaction
ROLLBACK;Rollback transaction
DDL 4
CREATE TABLE t (id INT PRIMARY KEY, name TEXT)Create table
ALTER TABLE t ADD COLUMN age INTAdd column
DROP TABLE tDrop table
CREATE INDEX idx_name ON t(name)Create index
💡 Tips
- AND has higher precedence than OR — use parentheses for complex conditions.
- Columns in GROUP BY must appear in SELECT (except aggregated columns).
- LIKE case-sensitivity depends on the database collation.
- Wrap data changes in BEGIN; and COMMIT only after verifying.
Official References
Commands are compiled from the official docs below. Click to verify the latest usage.
Maintained by LaoHand
Publicly updated on Aug 2, 2026, continuously proofread against official docs.
Found an error? Report it
Wrong command or description? Open an issue to help us fix it.
Found an error? Report it