SQL Cheat Sheet: Core Queries, Joins and Formatting Rules
A SQL cheat sheet with ready-to-run examples of SELECT, JOIN, GROUP BY, INSERT, UPDATE and DELETE, plus the SQL formatting rules that keep queries readable.
Updated
This SQL cheat sheet covers the statements that make up most day-to-day work: SELECT with filtering and sorting, JOIN, GROUP BY, and the three statements that change data, INSERT, UPDATE and DELETE. Every example is standard SQL that runs with little or no change on PostgreSQL, MySQL, SQLite and SQL Server. The final sections cover SQL formatting conventions.
The examples use two tables: customers (id, name, country) and orders (id, customer_id, total, created_at).
SELECT: reading data
- All columns:
SELECT * FROM customers; - Chosen columns:
SELECT name, country FROM customers; - Rename a column in the output:
SELECT name AS customer_name FROM customers; - Unique values:
SELECT DISTINCT country FROM customers; - Sort:
SELECT * FROM orders ORDER BY created_at DESC; - First ten rows:
SELECT * FROM orders ORDER BY total DESC LIMIT 10;
LIMIT works in PostgreSQL, MySQL and SQLite. SQL Server uses SELECT TOP 10 ... or OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY after an ORDER BY. Without ORDER BY, the order of rows is not guaranteed.
WHERE: filtering rows
| Condition | Example |
|---|---|
| Equals, not equals | WHERE country = 'DE', WHERE country <> 'DE' |
| Comparison | WHERE total >= 100 |
| Both, either | WHERE total > 50 AND country = 'US', WHERE a = 1 OR b = 2 |
| In a list | WHERE country IN ('US', 'CA', 'MX') |
| In a range, inclusive | WHERE total BETWEEN 10 AND 20 |
| Pattern match | WHERE name LIKE 'A%' |
| Missing value | WHERE country IS NULL, WHERE country IS NOT NULL |
Three things to remember. Strings use single quotes. In LIKE, % matches any run of characters and _ matches exactly one. And NULL is never equal to anything, including another NULL, so WHERE country = NULL matches no rows; always use IS NULL.
When mixing AND and OR, add parentheses. AND binds tighter, so a OR b AND c means a OR (b AND c).
JOIN: combining tables
- Matching rows only:
SELECT o.id, c.name, o.total FROM orders o INNER JOIN customers c ON c.id = o.customer_id; - All customers, with orders if any:
SELECT c.name, o.total FROM customers c LEFT JOIN orders o ON o.customer_id = c.id; - Customers with no orders:
SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
| Join type | Returns |
|---|---|
| INNER JOIN | Rows with a match in both tables |
| LEFT JOIN | Every left row, plus matches from the right or NULL |
| RIGHT JOIN | Every right row, plus matches from the left or NULL |
| FULL JOIN | Every row from both sides, matched where possible |
| CROSS JOIN | Every combination of left and right rows |
Plain JOIN means INNER JOIN. o and c are table aliases, which keep long queries short. A missing or wrong ON condition is the classic cause of a result with far too many rows.
GROUP BY: summarizing
The aggregate functions are COUNT, SUM, AVG, MIN and MAX.
- Count all rows:
SELECT COUNT(*) FROM orders; - Orders and revenue per customer:
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS revenue FROM orders GROUP BY customer_id; - Only customers with five or more orders:
SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id HAVING COUNT(*) >= 5; - Revenue per country:
SELECT c.country, SUM(o.total) AS revenue FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.country ORDER BY revenue DESC;
The rule: every column in the SELECT list must either appear in GROUP BY or be inside an aggregate function. COUNT(*) counts rows, while COUNT(column) skips rows where that column is NULL.
The order clauses run in
You write a query as SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT, but the database evaluates it logically in this order:
FROMandJOINbuild the working set of rows.WHEREfilters rows.GROUP BYforms groups.HAVINGfilters groups.SELECTcomputes the output columns.ORDER BYsorts.LIMITtrims.
This explains two common errors. An alias defined in SELECT cannot be used in WHERE, because WHERE runs first. And an aggregate cannot go in WHERE for the same reason; it belongs in HAVING.
INSERT, UPDATE and DELETE
- Add a row:
INSERT INTO customers (name, country) VALUES ('Ada', 'GB'); - Add several:
INSERT INTO customers (name, country) VALUES ('Grace', 'US'), ('Linus', 'FI'); - Change rows:
UPDATE customers SET country = 'UK' WHERE country = 'GB'; - Change several columns:
UPDATE orders SET total = 90, created_at = '2026-01-15' WHERE id = 17; - Remove rows:
DELETE FROM orders WHERE id = 17;
An UPDATE or DELETE without a WHERE clause affects every row in the table. Run the same WHERE as a SELECT first to see what will be touched, and wrap risky changes in a transaction: BEGIN, run the statement, check the row count, then COMMIT or ROLLBACK.
SQL formatting conventions
The database ignores layout, so formatting is purely for readers, including you in six months. No single official style exists, but these habits are widely shared:
- Uppercase keywords, lowercase names.
SELECT name FROM customersseparates the language from your schema at a glance. - One major clause per line.
SELECT,FROM,WHERE,GROUP BY,HAVINGandORDER BYeach start a new line at the left margin. - One column per line once the list is long, indented under
SELECT. - Each
JOINon its own line, with itsONcondition on the same line or indented beneath it. - Each
ANDorORon a new line, indented, so every condition can be read and commented out separately. - Use
snake_casenames and avoid reserved words such asorderoruseras table names. - Give tables short, meaningful aliases (
ofor orders,cfor customers) and qualify columns whenever more than one table is involved. - Write
ASfor column aliases.SUM(total) AS revenueis clearer thanSUM(total) revenue.
You do not need to do this by hand. The SQL Formatter takes a query pasted from a log, an ORM or a BI tool, usually one long line, and breaks it at each major clause with consistent indentation. You can choose two or four spaces and switch uppercase keywords on or off. It reformats the text only; it does not run the query or check it against a database.
Query results often leave the database as CSV. To turn an exported result into JSON for an API or a test fixture, use the JSON to CSV Converter in its CSV to JSON direction. Primary keys in these tables are often UUIDs; see what a UUID is.
Try it
Copy any single-line example from this page into the SQL Formatter and watch it split into clauses. Then paste the longest query in your own codebase and see whether the join conditions are what you thought they were.