Mental model for SQL queries

SQL is easier when you know two things: the order SQL actually runs each part of a query, and which window function fits which kind of question. This post covers both, with examples you can run in PostgreSQL.
The order SQL runs a query
You write SELECT first, but the database runs it almost last:
FROMandJOIN— pick the tablesWHERE— filter rowsGROUP BY— make groupsHAVING— filter groupsSELECT— work out columns, including window functionsDISTINCTORDER BYLIMIT/OFFSET
This explains common errors. For example, you can’t use a SELECT alias inside WHERE, because WHERE runs first. And you can’t filter on a window function in WHERE; you wrap the query and filter outside, as in the ranking example below.
Five kinds of window function
1. Looking across rows
LAG()→ look at the previous rowLEAD()→ look at the next row
2. Accumulating
SUM() OVER()→ running totalAVG() OVER()→ running or moving average
3. Ranking
ROW_NUMBER()→ 1, 2, 3, 4 (always unique)RANK()→ 1, 2, 2, 4 (ties share a rank, then a gap)DENSE_RANK()→ 1, 2, 2, 3 (ties, no gap)
4. Bucketing
NTILE(4)→ split rows into 4 equal groups (quartiles)
5. Distribution
PERCENT_RANK()→ where a row sits from 0 (lowest) to 1 (highest)CUME_DIST()→ share of rows at or below this value

The example table
All the examples use this sales table:
sales (
order_id INT,
customer_id INT,
region TEXT,
order_date DATE,
amount DECIMAL
)
Example questions and queries
“Show me running totals”
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM sales;
“Compare each order with the previous one”
SELECT
order_id,
order_date,
amount,
LAG(amount) OVER (ORDER BY order_date) AS prev_amount,
amount - LAG(amount) OVER (ORDER BY order_date) AS diff
FROM sales;
The first row has no previous order, so prev_amount and diff are NULL.
“Top 3 customers per region”
SELECT *
FROM (
SELECT
customer_id,
region,
SUM(amount) AS total_spent,
ROW_NUMBER() OVER (
PARTITION BY region
ORDER BY SUM(amount) DESC
) AS rn
FROM sales
GROUP BY customer_id, region
) t
WHERE rn <= 3;
The window function runs after GROUP BY, so it can rank the totals. The outer query filters on rn because WHERE can’t see window results in the same query.
“Which days have no sales?”
SELECT d::date AS missing_day
FROM generate_series(
(SELECT MIN(order_date) FROM sales),
(SELECT MAX(order_date) FROM sales),
INTERVAL '1 day'
) AS d
WHERE d::date NOT IN (SELECT order_date FROM sales);
generate_series builds a list of every date in the range, then the query keeps the dates with no orders. (This uses PostgreSQL. In other databases, use a calendar table.)
“Smooth the noise with a 3-day moving average”
WITH daily AS (
SELECT order_date, SUM(amount) AS day_total
FROM sales
GROUP BY order_date
)
SELECT
order_date,
day_total,
AVG(day_total) OVER (
ORDER BY order_date
RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW
) AS moving_avg_3_days
FROM daily;
Two details matter here. First, total the sales per day, so each row is one day. Second, use RANGE with an interval, not ROWS BETWEEN 2 PRECEDING. ROWS counts rows, so if a day is missing it would quietly average across 4 or more days.
“Remove duplicates, keep the latest”
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY order_date DESC
) AS rn
FROM sales
) t
WHERE rn = 1;
“Who improved month over month?”
WITH monthly AS (
SELECT
customer_id,
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS month_total
FROM sales
GROUP BY customer_id, DATE_TRUNC('month', order_date)
)
SELECT
customer_id,
month,
month_total,
month_total - LAG(month_total) OVER (
PARTITION BY customer_id
ORDER BY month
) AS growth
FROM monthly;
Total each customer’s spending per month first. Otherwise LAG compares single orders, not months.
Quick reference
| Question | Window function |
|---|---|
| Compare with previous/next | LAG / LEAD |
| Running total or moving average | SUM / AVG OVER |
| Top N per group | ROW_NUMBER with PARTITION BY |
| Remove duplicates | ROW_NUMBER, keep rn = 1 |
| Split into groups | NTILE |
| Percentile position | PERCENT_RANK / CUME_DIST |
One Response