SQL cheat sheet
Every example below uses the tables of our sample bookstore (authors, books, customers, orders, order_items) and is executed against it by our test suite with SQLite. Most of the syntax works unchanged in PostgreSQL and MySQL. Start with the SQL tutorial if you are new.
Query one tableAggregate and groupJoin tablesSubqueries, CTEs, expressionsChange dataDefine tables
Query one table
| Syntax | What it does | Example → result |
SELECT cols FROM t | Choose columns | SELECT title, price FROM books; |
SELECT DISTINCT | Unique rows only | SELECT DISTINCT genre FROM books; |
expr AS alias | Name a computed column | SELECT price * 2 AS doubled FROM books; |
WHERE | Filter rows | SELECT * FROM books WHERE price < 20; |
AND / OR / NOT | Combine conditions | SELECT * FROM books WHERE genre = 'Tech' AND NOT stock = 0; |
IN (...) | Match any value in a list | SELECT * FROM customers WHERE city IN ('Austin', 'Denver'); |
BETWEEN a AND b | Inclusive range | SELECT * FROM books WHERE year BETWEEN 2015 AND 2020; |
LIKE | Pattern match: % any run, _ one character | SELECT * FROM books WHERE title LIKE '%Paper%'; |
IS NULL | Test for missing values | SELECT name FROM customers WHERE email IS NULL; |
ORDER BY | Sort (ASC default, DESC descending) | SELECT title FROM books ORDER BY price DESC; |
LIMIT / OFFSET | Return a page of rows | SELECT title FROM books ORDER BY id LIMIT 5 OFFSET 5; |
Aggregate and group
| Syntax | What it does | Example → result |
count(*) | Count rows | SELECT count(*) FROM orders; |
sum() / avg() | Total and mean | SELECT sum(stock), avg(price) FROM books; |
min() / max() | Smallest and largest | SELECT min(year), max(year) FROM books; |
GROUP BY | One row per group | SELECT genre, count(*) FROM books GROUP BY genre; |
HAVING | Filter groups after aggregation | SELECT author_id FROM books GROUP BY author_id HAVING count(*) > 1; |
Join tables
| Syntax | What it does | Example → result |
JOIN ... ON | Matching rows from two tables | SELECT b.title, a.name FROM books b JOIN authors a ON a.id = b.author_id; |
LEFT JOIN | Keep every left row; NULLs where no match | SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id; |
Chained joins | Follow several foreign keys | SELECT c.name, b.title FROM orders o JOIN customers c ON c.id = o.customer_id JOIN order_items i ON i.order_id = o.id JOIN books b ON b.id = i.book_id; |
Subqueries, CTEs, expressions
| Syntax | What it does | Example → result |
Scalar subquery | Compare with a computed value | SELECT title FROM books WHERE price > (SELECT avg(price) FROM books); |
IN (SELECT ...) | Filter by another query | SELECT name FROM authors WHERE id IN (SELECT author_id FROM books); |
EXISTS | Related rows exist | SELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id); |
WITH (CTE) | Name a subquery | WITH cheap AS (SELECT * FROM books WHERE price < 15) SELECT count(*) FROM cheap; |
CASE WHEN | Conditional value | SELECT title, CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END AS status FROM books; |
Window function | Rank or total without collapsing rows | SELECT title, rank() OVER (ORDER BY price DESC) AS price_rank FROM books; |
coalesce() | First non-NULL value | SELECT coalesce(email, 'n/a') FROM customers; |
String functions | upper(), lower(), length(), substr(), || | SELECT upper(name), length(name) FROM authors; |
Date functions | Date arithmetic on ISO text dates | SELECT date('2025-10-02', '+7 days'); |
Change data
| Syntax | What it does | Example → result |
INSERT | Add a row | INSERT INTO authors (name, country) VALUES ('New Author', 'Canada'); |
UPDATE | Change matching rows (always use WHERE) | UPDATE books SET stock = stock + 5 WHERE id = 3; |
DELETE | Remove matching rows | DELETE FROM order_items WHERE qty = 0; |
UPSERT | Insert, or update on conflict | INSERT INTO authors (id, name) VALUES (1, 'Maya L.') ON CONFLICT(id) DO UPDATE SET name = excluded.name; |
RETURNING | Show affected rows (SQLite 3.35+) | DELETE FROM books WHERE stock = 0 RETURNING title; |
Transaction | All or nothing | BEGIN; UPDATE books SET price = price * 1.1; COMMIT; |
Define tables
| Syntax | What it does | Example → result |
CREATE TABLE | New table with constraints | CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE); |
ALTER TABLE ... ADD COLUMN | Add a column | ALTER TABLE books ADD COLUMN isbn TEXT; |
CREATE INDEX | Speed up lookups on a column | CREATE INDEX idx_books_genre ON books(genre); |
CREATE VIEW | Save a query under a name | CREATE VIEW in_stock AS SELECT * FROM books WHERE stock > 0; |
DROP TABLE | Delete a table and its data | DROP TABLE IF EXISTS tags; |
Compiled by Ethan Cole (pen name) with AI-assisted drafting; every example in the table is executed by our test suite. Related lessons: where, group by having, inner join, insert update delete.