Window Functions Beyond the Basics
Lesson opener
In one line: Window frames (ROWS / RANGE) - what “running” actually means.
Why it matters: Growth reports need “previous period” without a self-join.
Before this lesson: Window functions
Before you start
| Resource | Link |
|---|---|
| Previous | Upserts & write patterns |
| Next | Index types & when to use them |
| Prerequisites | Required: Window functions — ROW_NUMBER, PARTITION BY, basic running totals |
| Time | ~50 minutes |
What you will learn
- Window frames (
ROWS/RANGE) — what “running” actually means LAG/LEADfor period-over-period comparisonsFILTERon aggregates inside windows (and grouped queries)- Tie-handling with
RANK/DENSE_RANK— without re-teaching numbering from scratch
Refresher, not a repeat: If
OVER (PARTITION BY … ORDER BY …)is fuzzy, reopen sql10 — Window functions first. This lesson does not re-explainROW_NUMBERor basicPARTITION BY.
Frames — the missing mental model
A window function sees a frame: which peer rows are included while computing the current row.
[Running revenue with an explicit frame]
SELECT
sale_month,
revenue,
SUM(revenue) OVER (
ORDER BY sale_month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_rev
FROM (
SELECT sale_month, SUM(revenue) AS revenue
FROM sales
GROUP BY sale_month
) m
ORDER BY sale_month;Breaking it down:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW→ classic cumulative sumROWScounts physical rows in the ordered windowRANGEuses value range on theORDER BYexpression (peers with the same sort key behave differently)
Sliding window (last 3 months including current):
SUM(revenue) OVER (
ORDER BY sale_month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rev_last_3Default trap: If you write ORDER BY inside OVER without a frame clause, Postgres applies a default frame that often behaves like “from the start of the partition through the current peer group” for aggregates — being explicit avoids surprises in code review.
LAG and LEAD
[Compare this month to last month]
WHY: Growth reports need “previous period” without a self-join.
WHEN: MoM revenue, previous status, next appointment.
SELECT
customer_id,
sale_month,
revenue,
LAG(revenue) OVER (
PARTITION BY customer_id
ORDER BY sale_month
) AS prev_revenue,
LEAD(revenue) OVER (
PARTITION BY customer_id
ORDER BY sale_month
) AS next_revenue
FROM sales
ORDER BY customer_id, sale_month;With a default for the first row:
LAG(revenue, 1, 0) OVER (
PARTITION BY customer_id
ORDER BY sale_month
) AS prev_revenueBreaking it down:
LAG(col)→ value from the previous row in the window orderLEAD(col)→ value from the next row- Optional offset and default:
LAG(col, offset, default)
MoM change:
revenue - LAG(revenue, 1, 0) OVER (
PARTITION BY customer_id ORDER BY sale_month
) AS mom_changeFILTER on aggregates
[Conditional counts without bulky CASE]
WHY: CASE WHEN inside SUM works; FILTER reads cleaner in Postgres.
WHEN: “How many Gold vs churned in this window/group?”
SELECT
segment,
COUNT(*) AS total_customers,
COUNT(*) FILTER (WHERE churned IS FALSE) AS active_customers,
COUNT(*) FILTER (WHERE churned IS TRUE) AS churned_customers
FROM customers
GROUP BY segment;Inside a window:
SELECT
sale_month,
SUM(revenue) OVER (ORDER BY sale_month) AS running_all,
SUM(revenue) FILTER (WHERE revenue >= 100)
OVER (ORDER BY sale_month) AS running_big_sales
FROM (
SELECT sale_month, SUM(revenue) AS revenue
FROM sales
GROUP BY sale_month
) m;(FILTER with windows applies to the aggregate before the window framing — keep examples simple in practice work.)
Ties — RANK vs DENSE_RANK (quick, deliberate)
You met ranking ideas in sql10. Here is the tie behaviour only:
| Function | Ties | Next rank after a tie |
|---|---|---|
RANK() | Same rank | Skips (1, 1, 3) |
DENSE_RANK() | Same rank | No skip (1, 1, 2) |
ROW_NUMBER() | Never ties | Unique always — see sql10 |
SELECT
customer_id,
total_revenue,
RANK() OVER (ORDER BY total_revenue DESC) AS revenue_rank,
DENSE_RANK() OVER (ORDER BY total_revenue DESC) AS revenue_dense_rank
FROM customers;Use RANK when “competition ranking” matters; DENSE_RANK when gaps annoy the report consumer.
Essential commands
| Command / action | What it does |
|---|---|
ROWS BETWEEN … | Explicit physical frame |
RANGE BETWEEN … | Value-based frame |
LAG / LEAD | Previous / next row values |
FILTER (WHERE …) | Conditional aggregate |
RANK / DENSE_RANK | Ranking with ties |
Practice
Do this now:
- Build a monthly revenue series and a 3-row sliding sum with an explicit
ROWSframe. - Compute MoM change with
LAGpercustomer_id. - Write a
COUNT(*) FILTER (WHERE …)breakdown by segment. - Compare
RANKvsDENSE_RANKontotal_revenue. - Save as
exercises/answers/pg/06_windows_beyond.sql.
If step 1–2 fail because OVER syntax is unfamiliar, stop and redo sql10 before continuing.
Teacher walkthrough: frame + LAG for ops metrics
All figures illustrative.
Steps: Compute running total or WoW change with an explicit frame.
Failure example
Symptom: Wrong totals from default frame
Diagnosis: Assumed default frame matched the business window.
Correction: Write ROWS/RANGE explicitly; test on a tiny known table.
Validation: Re-run the lesson's verify query/EXPLAIN snippet and confirm expected plan or result.
Guided practice
LAG vs LEAD in one line?
Complete solution: LAG looks backward in the partition order; LEAD looks forward.
Independent practice
Acceptance criteria:
- Completed the lesson's practice queries on your lab database.
- One failure you hit (or a simulated one) documented with fix.
- Notes state when not to use this feature.
- Link forward to the next
pglesson.
Common mistakes
- Copying MySQL dialect unchanged.
- Skipping
EXPLAINwhen performance is the claim. - Changing production without a transaction/backup habit (pg10).
Checklist
- [ ] I can explain
ROWSvs why frame clauses should be explicit - [ ] I used
LAG/LEADfor a period comparison - [ ] I used
FILTERinstead of a bulkyCASEaggregate at least once - [ ] I did not need this lesson to re-learn
ROW_NUMBER— I used sql10 for that - [ ] Next: Index types