Selecting data
SELECT id, name, email
FROM users
ORDER BY created_at DESC
LIMIT 10;
SELECT DISTINCT country FROM users;
SELECT name AS customer, price * qty AS total
FROM orders;
Filtering
| Condition | Example |
|---|---|
| Equal / not equal | status = 'paid' · status <> 'paid' |
| In a list | country IN ('DE', 'FR', 'NL') |
| Range (inclusive) | total BETWEEN 10 AND 50 |
| Pattern | email LIKE '%@example.com' |
| Missing values | deleted_at IS NULL |
| Combine | a AND (b OR c) · NOT a |
column = NULL is never true. Comparisons with NULL return unknown, so always use IS NULL or IS NOT NULL.
Joins
| Join | Keeps |
|---|---|
INNER JOIN | Only rows that match on both sides |
LEFT JOIN | Every row from the left, matches from the right or NULL |
RIGHT JOIN | The mirror image of a left join |
FULL OUTER JOIN | All rows from both sides |
CROSS JOIN | Every combination of rows |
SELECT u.name, o.id AS order_id, o.total
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
-- users who have never ordered (anti-join)
SELECT u.*
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;
Grouping and aggregates
SELECT country,
COUNT(*) AS users,
AVG(age) AS avg_age
FROM users
WHERE active
GROUP BY country
HAVING COUNT(*) > 100
ORDER BY users DESC;
Clauses run in this order, which explains most “column not found” errors:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
WHERE filters rows before grouping; HAVING filters groups after it.
CTEs and window functions
A CTE (WITH) names a sub-query so the main query stays readable. Window functions compute across related rows without collapsing them.
-- monthly revenue with running total (date_trunc is PostgreSQL)
WITH monthly AS (
SELECT date_trunc('month', created_at) AS month,
SUM(total) AS revenue
FROM orders
GROUP BY 1
)
SELECT month,
revenue,
SUM(revenue) OVER (ORDER BY month) AS running_total,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;
-- the biggest order for each user
SELECT *
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS rn
FROM orders o
) ranked
WHERE rn = 1;
Changing data safely
INSERT INTO tags (name) VALUES ('git'), ('sql');
BEGIN;
UPDATE users SET plan = 'pro' WHERE id IN (12, 42);
-- check the result before making it permanent
SELECT id, plan FROM users WHERE id IN (12, 42);
COMMIT; -- or ROLLBACK;
DELETE FROM sessions WHERE expires_at < now();
Write the WHERE clause as a SELECT first. When it returns exactly the rows you expect, change it into UPDATE or DELETE.