The one-line mental model
SQL is a declarative language: you describe the result you want, the planner decides how to get it â so mastery means understanding join fan-out, window framing, and execution plans, not memorizing syntax.
You will be able to:
- Choose the correct JOIN type and spot accidental row multiplication
- Rewrite nested subqueries as readable CTE chains
- Use window functions for ranks, running totals, and period-over-period deltas
- Read an EXPLAIN ANALYZE plan enough to know when an index would help
Prerequisites
- !Basic SELECT, WHERE, and ORDER BY
- !What primary and foreign keys are
- !Aggregations with COUNT and SUM
What You'll Learn
- 1Predict the row count of a join before running it
- 2Structure multi-step analytics as CTEs instead of deep subquery nests
- 3Compute per-group rankings and moving statistics with window functions
- 4Recognize sequential scans and missing indexes in EXPLAIN output
How the engine actually processes a query
Every SELECT you write is parsed, planned, and executed. The logical plan preserves the semantics you declared; the physical planner then chooses join algorithms, access paths, and aggregation strategies. Understanding the clause order matters because it explains behavior that looks paradoxical at first: you cannot reference a column alias in the WHERE clause, and HAVING filters groups after aggregation while WHERE filters rows before it.
The logical evaluation order is roughly FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY, then LIMIT. That is why WHERE cannot use aggregate functions and why a filter on an aggregate must move to HAVING â or, in modern engines, into a QUALIFY-style window filter after the SELECT list is computed.
| Clause | Filters | Can use aggregates? | Can use window functions? |
|---|---|---|---|
| WHERE | Rows, before grouping | No | No |
| GROUP BY | Buckets rows | Yes, inside aggregates | No |
| HAVING | Groups, after aggregation | Yes | No |
| QUALIFY (some engines) | Rows after window computation | No | Yes |
JOIN types and the fan-out trap
Joining is the most common source of silent wrong numbers in analytics. An INNER JOIN keeps only matching pairs; a LEFT JOIN keeps every row of the left table and fills unmatched right columns with NULL; a FULL OUTER JOIN keeps everything from both sides. The danger is one-to-many: joining a customers table to an orders table and then summing order amounts before any deduplication multiplies values whenever a customer has several orders.
-- Employee and department, with unmatched employees preserved
SELECT
e.employee_id,
e.full_name,
e.salary,
d.department_name,
d.cost_center
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE e.active = TRUE;
-- Self-join to reach an employee's manager in the same table
SELECT
e.full_name AS employee,
m.full_name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id;
-- Anti-join: customers with zero orders (classic retention question)
SELECT c.customer_id, c.email
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
The anti-join pattern â LEFT JOIN plus a NULL check on the right table's key â appears constantly in churn and funnel analysis. A NOT EXISTS subquery expresses the same idea and often plans better on large tables because the planner can stop at the first match.
CTEs: making multi-step logic readable
Common Table Expressions let you name intermediate results and chain them linearly, which is dramatically easier to review than a five-deep subquery nest. They also give you a clean place to apply filters once, early, so every downstream step works on the same universe of rows.
WITH active_customers AS (
SELECT customer_id, segment, region
FROM customers
WHERE status = 'active'
AND created_at >= DATE '2024-01-01'
),
monthly_orders AS (
SELECT
customer_id,
DATE_TRUNC('month', ordered_at) AS month,
SUM(total_amount) AS revenue,
COUNT(*) AS order_count
FROM orders
WHERE ordered_at >= DATE '2024-01-01'
GROUP BY 1, 2
),
customer_monthly AS (
SELECT
ac.segment,
ac.region,
mo.month,
SUM(mo.revenue) AS segment_revenue,
COUNT(DISTINCT mo.customer_id) AS active_buyers
FROM active_customers ac
INNER JOIN monthly_orders mo
ON mo.customer_id = ac.customer_id
GROUP BY 1, 2, 3
)
SELECT
segment,
region,
month,
segment_revenue,
active_buyers,
segment_revenue / NULLIF(active_buyers, 0) AS revenue_per_buyer
FROM customer_monthly
ORDER BY month DESC, segment_revenue DESC;
Recursive CTEs handle hierarchies â org charts, category trees, bill-of-materials â by iterating a seed query until no new rows appear. They are rare in ad-hoc analysis but invaluable when the data itself is a graph stored in a relational schema.
Window functions: analytics without self-joins
Window functions compute a value across a related set of rows without collapsing them, which eliminates the class of bugs where you join an aggregate back to the grain and multiply rows. ROW_NUMBER, RANK, and DENSE_RANK differ only in how they treat ties; LAG and LEAD reach across periods; frame clauses like ROWS BETWEEN 6 PRECEDING AND CURRENT ROW build moving averages.
-- Rank earners within each department; note the tie behavior difference
SELECT
employee_id,
department,
salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS row_num,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_num,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank_num
FROM employees;
-- Running total and 7-day moving average of daily revenue
SELECT
order_date,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total,
AVG(revenue) OVER (
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM daily_revenue;
-- Month-over-month change via LAG
SELECT
month,
revenue,
LAG(revenue, 1) OVER (ORDER BY month) AS prev_month,
revenue - LAG(revenue, 1) OVER (ORDER BY month) AS mom_delta,
revenue / NULLIF(LAG(revenue, 1) OVER (ORDER BY month), 0) - 1 AS mom_pct
FROM monthly_revenue
ORDER BY month;
A frequent production pattern is "latest record per user": ROW_NUMBER ordered by updated_at descending, partitioned by user id, filtered to rank 1 in an outer query or CTE. That single idiom replaces messy correlated subqueries in almost every snapshot-style analysis.
Aggregation patterns that scale
GROUP BY remains the workhorse, but the details decide whether a query finishes in seconds or times out. COUNT(*) counts rows; COUNT(column) skips NULLs; COUNT(DISTINCT id) forces a distinct aggregation that is expensive at scale. GROUPING SETS lets you compute several levels of hierarchy in one scan instead of three separate queries.
SELECT
COALESCE(department, 'All departments') AS department,
COALESCE(region, 'All regions') AS region,
COUNT(*) AS headcount,
SUM(salary) AS total_comp
FROM employees
GROUP BY GROUPING SETS (
(department, region),
(department),
(region),
()
);
-- Top-N per group without a lateral join (Postgres-flavored)
SELECT *
FROM (
SELECT
department,
employee_id,
salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees
) ranked
WHERE rn <= 3;
Reading EXPLAIN before blaming the database
A slow query is rarely slow because the database is underpowered; it is slow because the plan is wrong. EXPLAIN (or EXPLAIN ANALYZE on engines that support it) shows the actual execution tree: which joins ran first, whether an index was used, and how many rows the optimizer estimated versus how many it actually saw. Learning to read this output is the single highest-leverage skill for anyone who writes SQL against a production warehouse.
The most common red flags are sequential scans on large tables where an index exists, nested-loop joins over high-cardinality keys, and estimated row counts that diverge from actual counts by more than an order of magnitude. That last signal â estimate versus actual â usually means stale statistics; refreshing them is often all it takes. Before filing a ticket against the data platform team, spend five minutes with the plan. The bottleneck is almost always visible.
When a query is slow, the plan tells you whether the engine scanned a table you meant to index, misestimated a join cardinality, or spilled a hash join to disk. EXPLAIN ANALYZE runs the query and reports actual rows next to estimates; a gap of two orders of magnitude between estimate and actual is a signal to refresh statistics or rewrite the predicate.
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT c.customer_id, COUNT(o.order_id) AS lifetime_orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE c.region = 'West'
AND o.ordered_at >= DATE '2024-01-01'
GROUP BY c.customer_id;
-- Supporting indexes for the pattern above
CREATE INDEX idx_orders_customer_ordered
ON orders (customer_id, ordered_at);
CREATE INDEX idx_customers_region
ON customers (region) WHERE status = 'active';
Select only the columns you need â pulling forty columns from a wide fact table to compute one sum wastes I/O and defeats projection pushdown in modern engines. And when you see SELECT * in a maintained production view, treat it as a bug: upstream schema changes become downstream breakage.