SQL Cheat Sheet: The Statements You Use Every Day
The core SQL statements for querying and changing data, grouped by task. The exact syntax varies slightly between databases (PostgreSQL, MySQL, SQLite, SQL Server), but the fundamentals below are near-universal. To tidy a messy query, use the SQL formatter.
Updated 2026-07-06
Querying (SELECT)
| Statement | What it does |
|---|---|
| SELECT * FROM t | Return every column and row from table t |
| SELECT a, b FROM t | Return only columns a and b |
| SELECT DISTINCT a FROM t | Return unique values of a |
| ... WHERE a = 5 | Filter rows where a equals 5 |
| ... ORDER BY a DESC | Sort by a, descending |
| ... LIMIT 10 | Return at most 10 rows |
| ... OFFSET 20 | Skip the first 20 rows (paging) |
| SELECT COUNT(*) FROM t | Count rows |
| SELECT SUM(a), AVG(a) FROM t | Aggregate: total and average of a |
| ... GROUP BY category | Group rows to aggregate per category |
| ... HAVING COUNT(*) > 5 | Filter groups (WHERE for aggregates) |
Filtering (WHERE)
| Statement | What it does |
|---|---|
| WHERE a IN (1, 2, 3) | Match any value in a list |
| WHERE a BETWEEN 1 AND 9 | Match a range (inclusive) |
| WHERE name LIKE 'A%' | Pattern match: starts with A (% = any chars) |
| WHERE name LIKE '_at' | _ matches exactly one character |
| WHERE a IS NULL | Match rows where a has no value |
| WHERE a > 5 AND b < 10 | Combine conditions with AND / OR |
Joining tables
| Statement | What it does |
|---|---|
| INNER JOIN u ON t.id = u.tid | Rows with a match in both tables |
| LEFT JOIN u ON t.id = u.tid | All rows from the left table, matched or not |
| RIGHT JOIN u ON t.id = u.tid | All rows from the right table |
| FULL JOIN u ON t.id = u.tid | All rows from both tables |
Changing data
| Statement | What it does |
|---|---|
| INSERT INTO t (a, b) VALUES (1, 2) | Add a new row |
| UPDATE t SET a = 5 WHERE id = 1 | Change existing rows (mind the WHERE!) |
| DELETE FROM t WHERE id = 1 | Remove rows (mind the WHERE!) |
Schema (tables & indexes)
| Statement | What it does |
|---|---|
| CREATE TABLE t (id INT, name TEXT) | Create a new table |
| ALTER TABLE t ADD col TEXT | Add a column |
| DROP TABLE t | Delete a table and all its data |
| CREATE INDEX idx ON t (a) | Add an index to speed up lookups on a |
A safety habit worth keeping: always write the WHERE clause of an UPDATE or DELETE first. Running one without a WHERE changes or deletes every row in the table.
Related tools