SQL Commands

SQL commands cheatsheet.

Query, filter, aggregate, join and modify — the core SQL statements, ready to copy and adapt.

Querying
SELECT * FROM table;Return every column and row from a table
SELECT col1, col2 FROM table;Return only specific columns
SELECT * FROM table WHERE col = 'x';Filter rows by a condition
SELECT DISTINCT col FROM table;Return unique values of a column
SELECT * FROM table ORDER BY col DESC;Sort results by a column
SELECT * FROM table LIMIT 10;Return at most 10 rows
Aggregating
SELECT COUNT(*) FROM table;Count the rows in a table
SELECT col, COUNT(*) FROM table GROUP BY col;Count rows per group
SELECT AVG(col) FROM table;Average a numeric column
SELECT col, SUM(amt) FROM table GROUP BY col HAVING SUM(amt) > 100;Filter groups by an aggregate
Joining
SELECT * FROM a JOIN b ON a.id = b.a_id;Inner join two tables on a key
SELECT * FROM a LEFT JOIN b ON a.id = b.a_id;Keep all rows from the left table
SELECT * FROM a, b WHERE a.id = b.a_id;Older comma-style join syntax
Modifying
INSERT INTO table (a, b) VALUES (1, 'x');Add a new row
UPDATE table SET col = 'x' WHERE id = 1;Change values in matching rows
DELETE FROM table WHERE id = 1;Remove matching rows
CREATE TABLE t (id INT, name TEXT);Create a new table
ALTER TABLE t ADD COLUMN c INT;Add a column to a table
DROP TABLE t;Delete a table and its data
These use standard ANSI SQL syntax; a few details (LIMIT vs TOP, quoting) vary between PostgreSQL, MySQL, SQLite and SQL Server.

The statements behind every query

Most SQL work is built from a few patterns: SELECT … WHERE to read and filter, GROUP BY with aggregates like COUNT and SUM to summarise, JOIN to combine tables, and INSERT/UPDATE/DELETE to change data. Swap in your own table and column names as you copy.

FAQ

What's the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only rows with a match in both tables; LEFT JOIN returns all rows from the left table and fills in NULLs where the right table has no match.
How do I limit the number of rows returned?
Use LIMIT 10 in PostgreSQL, MySQL and SQLite. SQL Server uses SELECT TOP 10 … instead.

More cheatsheets