SQL Cheat Sheet
SQL quick reference. Queries, joins, aggregation, and common functions. Bookmark this page or print it.
Basic Queries
SELECT * FROM tableSelect allSELECT col1, col2 FROM tableSelect colsSELECT DISTINCT col FROM tableUnique valuesSELECT * FROM t WHERE col > 5FilterSELECT * FROM t ORDER BY col DESCSortSELECT * FROM t LIMIT 10 OFFSET 5PaginateJoins
INNER JOINMatching rowsLEFT JOINAll left + matching rightRIGHT JOINAll right + matching leftFULL OUTER JOINAll rows bothCROSS JOINCartesian productSELF JOINJoin to itselfAggregation
COUNT(*) / COUNT(DISTINCT col)CountSUM(col) / AVG(col)Sum / AvgMIN(col) / MAX(col)Min / MaxGROUP BY colGroup rowsHAVING COUNT(*) > 5Filter groupsModifying
INSERT INTO t (c1) VALUES (v1)InsertUPDATE t SET c1 = v1 WHERE ...UpdateDELETE FROM t WHERE ...DeleteCREATE TABLE t (id INT PRIMARY KEY)Create tableALTER TABLE t ADD col TYPEAdd columnDROP TABLE tDelete tableFunctions
COALESCE(a, b)First non-nullCASE WHEN x THEN y ELSE z ENDConditionalCAST(col AS TYPE)Type conversionCONCAT(a, b)String concatSUBSTRING(col, 1, 5)SubstringNOW() / CURRENT_DATECurrent date