elefcode
← All cheat sheets

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 table
SELECT id, name FROM users;Specific columns
SELECT DISTINCT country FROM users;Unique values only
SELECT name AS full_name FROM users;Rename a column in the result
LIMIT 10Return at most 10 rows
ORDER BY created_at DESCSort results (DESC = newest first)

Filtering

WHERE age > 18Basic comparison
WHERE name LIKE 'A%'Pattern match — starts with A
WHERE id IN (1, 2, 3)Match any value in a list
WHERE age BETWEEN 18 AND 30Inclusive range
WHERE 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 tables
LEFT JOIN orders ON ...All left rows, plus matches (NULL where none)
RIGHT JOIN orders ON ...All right rows, plus matches
FULL OUTER JOIN orders ON ...All rows from both sides
CROSS JOIN sizesEvery combination of both tables

Aggregation

COUNT(*)Number of rows
SUM(amount) / AVG(amount)Total / average of a column
MIN(x) / MAX(x)Smallest / largest value
GROUP BY countryCollapse rows into groups
HAVING COUNT(*) > 3Filter groups (WHERE filters rows)

Modifying data

INSERT INTO users (name) VALUES ('Ada');Add a row
UPDATE users SET name = 'Ada' WHERE id = 1;Change existing rows
DELETE FROM users WHERE id = 1;Remove rows (always use WHERE)
TRUNCATE TABLE users;Delete every row, fast and unlogged

Tables & indexes

CREATE TABLE users (id INT PRIMARY KEY, name TEXT);Create a table
ALTER TABLE users ADD COLUMN email TEXT;Add a column
DROP TABLE users;Delete a table entirely
CREATE INDEX idx_name ON users(name);Speed up lookups on a column

More cheat sheets