SQL Cheatsheet - Common Query Syntax & Examples
For developers who write SQL that is both business-correct and fast. The traps are usually not in the syntax itself but in NULL propagation, filtering after GROUP BY requiring HAVING, and where window functions stop overlapping plain aggregation. By the end you can write correct queries with grouping and filtering clauses, use window functions for row numbers and in-group ranking instead of self-joins, dodge NULL comparisons and aggregation pitfalls, and wrap multi-statement work in transactions for atomicity.
Basic Query 6
SELECT * FROM usersSELECT name, age FROM usersSELECT * FROM users WHERE age > 18SELECT DISTINCT city FROM usersSELECT * FROM users LIMIT 10 OFFSET 20SELECT * FROM users ORDER BY age DESCFiltering & Logic 6
WHERE name LIKE 'A%'WHERE name LIKE '%son'WHERE age BETWEEN 18 AND 30WHERE id IN (1, 2, 3)WHERE a IS NULLWHERE a AND b OR cAggregation & Grouping 5
SELECT COUNT(*) FROM usersSELECT AVG(age) FROM usersSELECT city, COUNT(*) FROM users GROUP BY cityHAVING COUNT(*) > 5SELECT MAX(age), MIN(age) FROM usersJOIN 5
FROM a JOIN b ON a.id = b.a_idFROM a LEFT JOIN b ON a.id = b.a_idFROM a RIGHT JOIN b ON a.id = b.a_idFROM a CROSS JOIN bSELECT * FROM a NATURAL JOIN bWindow Functions 4
ROW_NUMBER() OVER (ORDER BY age)RANK() OVER (PARTITION BY city ORDER BY age)SUM(amount) OVER (PARTITION BY user_id)LAG(price) OVER (ORDER BY date)DML & Transactions 5
INSERT INTO t (a, b) VALUES (1, 'x')UPDATE t SET a = 2 WHERE id = 1DELETE FROM t WHERE id = 1BEGIN; ... COMMIT;ROLLBACK;DDL 4
CREATE TABLE t (id INT PRIMARY KEY, name TEXT)ALTER TABLE t ADD COLUMN age INTDROP TABLE tCREATE INDEX idx_name ON t(name)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
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Aug 2, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us