SQL Cheatsheet
SQL is the language for querying relational databases. This cheatsheet covers selects, joins, filtering, aggregation, and more.
SQL (Structured Query Language) is the standard language for working with relational databases. This cheatsheet covers the core statements.
Select
Read data from tables.
SELECT * FROM users;
SELECT name, email FROM users;
SELECT DISTINCT country FROM users;
SELECT name AS full_name FROM users;
Filtering
Narrow down rows with WHERE.
SELECT * FROM users WHERE age > 18;
SELECT * FROM users WHERE country = 'UK';
SELECT * FROM users WHERE name LIKE 'A%';
SELECT * FROM users WHERE id IN (1, 2, 3);
SELECT * FROM users WHERE age BETWEEN 18 AND 30;
Sorting & Limiting
Order and paginate results.
SELECT * FROM users ORDER BY created_at DESC;
SELECT * FROM users ORDER BY name ASC LIMIT 10;
SELECT * FROM users LIMIT 10 OFFSET 20;
Insert
Add new rows.
INSERT INTO users (name, email)
VALUES ('Ada', 'ada@example.com');
Update
Modify existing rows.
UPDATE users
SET name = 'Ada L.'
WHERE id = 1;
Delete
Remove rows.
DELETE FROM users WHERE id = 1;
Joins
Combine data across tables.
SELECT o.id, u.name
FROM orders o
INNER JOIN users u ON o.user_id = u.id;
SELECT u.name, o.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
Aggregation
Summarize data with GROUP BY.
SELECT country, COUNT(*) AS total
FROM users
GROUP BY country
HAVING COUNT(*) > 5;
SELECT AVG(age), MAX(age), MIN(age) FROM users;
Subqueries
Query within a query.
SELECT name FROM users
WHERE id IN (
SELECT user_id FROM orders WHERE total > 100
);
SQL is essential for any data-driven application. Master selects and joins first, then explore indexes, transactions, and window functions.
For full documentation, see https://www.postgresql.org/docs/