Rana Maninder Singh
Lesson 6 of 11PostgreSQL

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

ResourceLink
PreviousUpserts & write patterns
NextIndex types & when to use them
PrerequisitesRequired: 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 / LEAD for period-over-period comparisons
  • FILTER on 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-explain ROW_NUMBER or basic PARTITION 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:

Sliding window (last 3 months including current):

SUM(revenue) OVER (
  ORDER BY sale_month
  ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rev_last_3

Default 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_revenue

Breaking it down:

MoM change:

revenue - LAG(revenue, 1, 0) OVER (
  PARTITION BY customer_id ORDER BY sale_month
) AS mom_change

FILTER 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:

FunctionTiesNext rank after a tie
RANK()Same rankSkips (1, 1, 3)
DENSE_RANK()Same rankNo skip (1, 1, 2)
ROW_NUMBER()Never tiesUnique 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 / actionWhat it does
ROWS BETWEEN …Explicit physical frame
RANGE BETWEEN …Value-based frame
LAG / LEADPrevious / next row values
FILTER (WHERE …)Conditional aggregate
RANK / DENSE_RANKRanking with ties

Practice

Do this now:

  1. Build a monthly revenue series and a 3-row sliding sum with an explicit ROWS frame.
  2. Compute MoM change with LAG per customer_id.
  3. Write a COUNT(*) FILTER (WHERE …) breakdown by segment.
  4. Compare RANK vs DENSE_RANK on total_revenue.
  5. 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:

Common mistakes

  1. Copying MySQL dialect unchanged.
  2. Skipping EXPLAIN when performance is the claim.
  3. Changing production without a transaction/backup habit (pg10).

Checklist

  • [ ] I can explain ROWS vs why frame clauses should be explicit
  • [ ] I used LAG/LEAD for a period comparison
  • [ ] I used FILTER instead of a bulky CASE aggregate at least once
  • [ ] I did not need this lesson to re-learn ROW_NUMBER — I used sql10 for that
  • [ ] Next: Index types