SQL Cheat Sheet

SQL cheat sheet: syntax and examples of common statements — SELECT, JOIN, GROUP BY, INSERT, UPDATE, DELETE, aggregates and constraints — for quick lookup while writing queries.

StatementMeaningExample
SELECTSelect columns (* for all)SELECT id, name FROM users
FROMSpecify source tableFROM orders
WHERERow filter conditionWHERE status = 'paid'
GROUP BYGroup rows for aggregationGROUP BY category
HAVINGFilter grouped resultsHAVING COUNT(*) > 1
ORDER BYSort (ASC/DESC)ORDER BY created_at DESC
LIMITLimit number of rowsLIMIT 10
OFFSETSkip first N rows (paging)OFFSET 20
DISTINCTReturn distinct valuesSELECT DISTINCT city
JOINInner join two tablesFROM a JOIN b ON a.id = b.a_id
LEFT JOINLeft join, keep all left rowsFROM a LEFT JOIN b ON a.id = b.a_id
RIGHT JOINRight join, keep all right rowsFROM a RIGHT JOIN b ON a.id = b.a_id
INNER JOINInner join (same as JOIN)FROM a INNER JOIN b ON a.id = b.a_id
ONJoin conditionON a.id = b.a_id
ASTable or column aliasSELECT name AS 姓名
INSERT INTOInsert a rowINSERT INTO users (name) VALUES ('Tom')
UPDATEUpdate rowsUPDATE users SET name = 'Tom' WHERE id = 1
DELETEDelete rowsDELETE FROM users WHERE id = 1
CREATE TABLECreate a tableCREATE TABLE t (id INT PRIMARY KEY)
ALTER TABLEAlter table structureALTER TABLE t ADD COLUMN age INT
DROP TABLEDrop a tableDROP TABLE t
PRIMARY KEYPrimary key constraintid INT PRIMARY KEY
FOREIGN KEYForeign key constraintFOREIGN KEY (a_id) REFERENCES a(id)
INDEXCreate index to speed up queryCREATE INDEX idx_name ON users(name)
UNIONCombine two result sets (distinct)SELECT a FROM t1 UNION SELECT a FROM t2
LIKEPattern match (% any, _ one)WHERE name LIKE 'T%'
INValue in a setWHERE status IN ('paid','done')
BETWEENInclusive rangeWHERE age BETWEEN 18 AND 30
NULL / IS NULLNull check (cannot use =)WHERE deleted_at IS NULL
COUNT / SUM / AVGAggregate functionsSELECT COUNT(*) FROM users
CASE WHENConditional expressionCASE WHEN age>18 THEN 'adult' ELSE 'minor' END
EXPLAINShow execution planEXPLAIN SELECT * FROM users

Frequently Asked Questions

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows matching in both tables; LEFT JOIN returns all rows from the left table, filling right-side columns with NULL when unmatched. Use LEFT JOIN to keep every master record, INNER JOIN for the intersection.

What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after GROUP BY and can reference aggregates (e.g. COUNT(*)). You cannot use aggregate functions in WHERE.

What is the difference between % and _ in LIKE?

% matches any length (including zero) of characters; _ matches exactly one character. 'T%' matches any string starting with T; 'T_m' matches T, one char, then m (e.g. Tom).

How do I test for NULL?

NULL means unknown and cannot be tested with = NULL; use IS NULL / IS NOT NULL. In most databases comparing NULL to anything yields unknown (not true), which is a common trap.