SQL commands cheatsheet.
Query, filter, aggregate, join and modify — the core SQL statements, ready to copy and adapt.
SELECT * FROM table;Return every column and row from a tableSELECT col1, col2 FROM table;Return only specific columnsSELECT * FROM table WHERE col = 'x';Filter rows by a conditionSELECT DISTINCT col FROM table;Return unique values of a columnSELECT * FROM table ORDER BY col DESC;Sort results by a columnSELECT * FROM table LIMIT 10;Return at most 10 rowsSELECT COUNT(*) FROM table;Count the rows in a tableSELECT col, COUNT(*) FROM table GROUP BY col;Count rows per groupSELECT AVG(col) FROM table;Average a numeric columnSELECT col, SUM(amt) FROM table GROUP BY col HAVING SUM(amt) > 100;Filter groups by an aggregateSELECT * FROM a JOIN b ON a.id = b.a_id;Inner join two tables on a keySELECT * FROM a LEFT JOIN b ON a.id = b.a_id;Keep all rows from the left tableSELECT * FROM a, b WHERE a.id = b.a_id;Older comma-style join syntaxINSERT INTO table (a, b) VALUES (1, 'x');Add a new rowUPDATE table SET col = 'x' WHERE id = 1;Change values in matching rowsDELETE FROM table WHERE id = 1;Remove matching rowsCREATE TABLE t (id INT, name TEXT);Create a new tableALTER TABLE t ADD COLUMN c INT;Add a column to a tableDROP TABLE t;Delete a table and its dataFour patterns cover most queries
SQL looks vast, but everyday work leans on four patterns. SELECT … WHERE reads and filters rows; GROUP BY with aggregates like COUNT, SUM and AVG summarises data into totals and averages; JOIN combines rows from related tables; and INSERT, UPDATE and DELETE change data. Recognising which of these a question maps to is most of the battle — "how many orders per customer" is a GROUP BY, "customers with their latest order" is a JOIN.
Joins are where it clicks
The concept that unlocks real queries is the JOIN. An INNER JOIN keeps only rows that match in both tables, while a LEFT JOIN keeps every row from the first table even when there's no match on the right — which is how you find, say, customers who haven't ordered anything. Getting the difference between these two straight resolves a large share of "my query is missing rows" or "my query has too many rows" confusion.
Change data carefully
One habit will save you real pain: an UPDATE or DELETE without a WHERE clause affects every row in the table. Before running either, it's worth writing the matching SELECT … WHERE first to see exactly which rows you'll touch, then converting it. Run inside a transaction when your database supports it, so a mistake can be rolled back. Want cleaner queries to read? Paste them into the SQL formatter to indent and align them.