TetSharing

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

SyntaxWhat it doesExample → result
SELECT cols FROM tChoose columnsSELECT title, price FROM books;
SELECT DISTINCTUnique rows onlySELECT DISTINCT genre FROM books;
expr AS aliasName a computed columnSELECT price * 2 AS doubled FROM books;
WHEREFilter rowsSELECT * FROM books WHERE price < 20;
AND / OR / NOTCombine conditionsSELECT * FROM books WHERE genre = 'Tech' AND NOT stock = 0;
IN (...)Match any value in a listSELECT * FROM customers WHERE city IN ('Austin', 'Denver');
BETWEEN a AND bInclusive rangeSELECT * FROM books WHERE year BETWEEN 2015 AND 2020;
LIKEPattern match: % any run, _ one characterSELECT * FROM books WHERE title LIKE '%Paper%';
IS NULLTest for missing valuesSELECT name FROM customers WHERE email IS NULL;
ORDER BYSort (ASC default, DESC descending)SELECT title FROM books ORDER BY price DESC;
LIMIT / OFFSETReturn a page of rowsSELECT title FROM books ORDER BY id LIMIT 5 OFFSET 5;

Aggregate and group

SyntaxWhat it doesExample → result
count(*)Count rowsSELECT count(*) FROM orders;
sum() / avg()Total and meanSELECT sum(stock), avg(price) FROM books;
min() / max()Smallest and largestSELECT min(year), max(year) FROM books;
GROUP BYOne row per groupSELECT genre, count(*) FROM books GROUP BY genre;
HAVINGFilter groups after aggregationSELECT author_id FROM books GROUP BY author_id HAVING count(*) > 1;

Join tables

SyntaxWhat it doesExample → result
JOIN ... ONMatching rows from two tablesSELECT b.title, a.name FROM books b JOIN authors a ON a.id = b.author_id;
LEFT JOINKeep every left row; NULLs where no matchSELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;
Chained joinsFollow several foreign keysSELECT 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

SyntaxWhat it doesExample → result
Scalar subqueryCompare with a computed valueSELECT title FROM books WHERE price > (SELECT avg(price) FROM books);
IN (SELECT ...)Filter by another querySELECT name FROM authors WHERE id IN (SELECT author_id FROM books);
EXISTSRelated rows existSELECT name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
WITH (CTE)Name a subqueryWITH cheap AS (SELECT * FROM books WHERE price < 15) SELECT count(*) FROM cheap;
CASE WHENConditional valueSELECT title, CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END AS status FROM books;
Window functionRank or total without collapsing rowsSELECT title, rank() OVER (ORDER BY price DESC) AS price_rank FROM books;
coalesce()First non-NULL valueSELECT coalesce(email, 'n/a') FROM customers;
String functionsupper(), lower(), length(), substr(), ||SELECT upper(name), length(name) FROM authors;
Date functionsDate arithmetic on ISO text datesSELECT date('2025-10-02', '+7 days');

Change data

SyntaxWhat it doesExample → result
INSERTAdd a rowINSERT INTO authors (name, country) VALUES ('New Author', 'Canada');
UPDATEChange matching rows (always use WHERE)UPDATE books SET stock = stock + 5 WHERE id = 3;
DELETERemove matching rowsDELETE FROM order_items WHERE qty = 0;
UPSERTInsert, or update on conflictINSERT INTO authors (id, name) VALUES (1, 'Maya L.') ON CONFLICT(id) DO UPDATE SET name = excluded.name;
RETURNINGShow affected rows (SQLite 3.35+)DELETE FROM books WHERE stock = 0 RETURNING title;
TransactionAll or nothingBEGIN; UPDATE books SET price = price * 1.1; COMMIT;

Define tables

SyntaxWhat it doesExample → result
CREATE TABLENew table with constraintsCREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
ALTER TABLE ... ADD COLUMNAdd a columnALTER TABLE books ADD COLUMN isbn TEXT;
CREATE INDEXSpeed up lookups on a columnCREATE INDEX idx_books_genre ON books(genre);
CREATE VIEWSave a query under a nameCREATE VIEW in_stock AS SELECT * FROM books WHERE stock > 0;
DROP TABLEDelete a table and its dataDROP TABLE IF EXISTS tags;

Official docs

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.