SQL Cheat Sheet
Quick reference from FreeCodingCourses.com
Query basics
SELECT name, email FROM users;- pick columns from a table.
SELECT * FROM users;- every column. Fine for exploring, avoid in real queries.
SELECT DISTINCT country FROM users;- unique values only.
SELECT name AS full_name FROM users;- rename a column in the output.
SELECT COUNT(*) FROM users;- count rows.
Filter and sort
WHERE age >= 18- keep rows that match.
WHERE country = 'US' AND active = true- combine with AND / OR.
WHERE name LIKE 'A%'- pattern match. % is any run of characters.
WHERE country IN ('US', 'UK')- match any value in a list.
WHERE email IS NULL- test for NULL with IS, never = .
ORDER BY created_at DESC LIMIT 10- sort newest first, take 10.
Joins
FROM orders o JOIN users u ON u.id = o.user_id- INNER JOIN: rows that match in both.
LEFT JOIN payments p ON p.order_id = o.id- all left rows, NULLs where no match.
SELECT u.name, o.total FROM ...- qualify columns with the table alias.
Group and aggregate
SELECT country, COUNT(*) FROM users GROUP BY country- one row per group.
SUM(total) AVG(total) MAX(total) MIN(total)- the common aggregates.
GROUP BY country HAVING COUNT(*) > 100- HAVING filters groups; WHERE filters rows.
Change data
INSERT INTO users (name, email) VALUES ('Ada', '[email protected]');- add a row.
UPDATE users SET active = false WHERE id = 5;- change matching rows.
DELETE FROM users WHERE id = 5;- remove matching rows.
Create a table
CREATE TABLE users ( id SERIAL PRIMARY KEY, email TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT now() );- columns, types, and constraints.
ALTER TABLE users ADD COLUMN age INT;- add a column later.
Unlock the full SQL cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.