Languages
SQL Cheat Sheet — Query Syntax Reference
The SQL statements and clauses you reach for most, with a one-line explanation of each.
Put it into practice with the matching tool.
Format SQL →Advertisement
Selecting data
SELECT * FROM users;All columns from a tableSELECT id, name FROM users;Specific columnsSELECT DISTINCT country FROM users;Unique values onlySELECT name AS full_name FROM users;Rename a column in the resultLIMIT 10Return at most 10 rowsORDER BY created_at DESCSort results (DESC = newest first)Filtering
WHERE age > 18Basic comparisonWHERE name LIKE 'A%'Pattern match — starts with AWHERE id IN (1, 2, 3)Match any value in a listWHERE age BETWEEN 18 AND 30Inclusive rangeWHERE email IS NULLTest for NULL (never use = NULL)WHERE a = 1 AND b = 2Combine conditions (also OR, NOT)Joins
INNER JOIN orders ON orders.user_id = users.idOnly rows matching in both tablesLEFT JOIN orders ON ...All left rows, plus matches (NULL where none)RIGHT JOIN orders ON ...All right rows, plus matchesFULL OUTER JOIN orders ON ...All rows from both sidesCROSS JOIN sizesEvery combination of both tablesAggregation
COUNT(*)Number of rowsSUM(amount) / AVG(amount)Total / average of a columnMIN(x) / MAX(x)Smallest / largest valueGROUP BY countryCollapse rows into groupsHAVING COUNT(*) > 3Filter groups (WHERE filters rows)Modifying data
INSERT INTO users (name) VALUES ('Ada');Add a rowUPDATE users SET name = 'Ada' WHERE id = 1;Change existing rowsDELETE FROM users WHERE id = 1;Remove rows (always use WHERE)TRUNCATE TABLE users;Delete every row, fast and unloggedTables & indexes
CREATE TABLE users (id INT PRIMARY KEY, name TEXT);Create a tableALTER TABLE users ADD COLUMN email TEXT;Add a columnDROP TABLE users;Delete a table entirelyCREATE INDEX idx_name ON users(name);Speed up lookups on a column