Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 07 / Stage 2

Window functions

Goal: Calculate across related rows without collapsing them — rankings, previous-row comparisons, running totals and moving averages — and know exactly when in a query windows are evaluated. Time: ~2 hours

What you will learn

  • OVER and PARTITION BY — and how a window differs from GROUP BY
  • Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE
  • LAG and LEAD: looking at the previous and next row
  • FIRST_VALUE and LAST_VALUE — and why LAST_VALUE surprises everyone
  • Ordinary aggregates as windows: running totals, share of total
  • Window frames: ROWS BETWEEN ..., moving averages
  • The WINDOW clause: name a window once, reuse it
  • Where windows are evaluated — and how to filter on their results

Everything runs on shopdb. Drifted? psql -d shopdb -f shopdb.sql.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Each topic above carries its own exercise and solution — open a topic and scroll to its exercise. All 8 exercises are also listed on the SQL Practice page.

Common mistakes

Mistake What happens Fix
Filtering a window result in WHERE window functions are not allowed in WHERE CTE/subquery, filter outside
LAST_VALUE with the default frame Echoes the current row ROWS BETWEEN ... UNBOUNDED FOLLOWING, or flip to FIRST_VALUE
RANK where one-per-group is required Ties produce several "rank 1" rows ROW_NUMBER
Expecting GROUP BY behaviour from OVER Rows "duplicated" (they were never collapsed) Windows keep every row — that's the point
Running total with ties under RANGE default Tied rows share a total ROWS BETWEEN for physical-row accumulation
Same OVER pasted five times Drift when one copy is edited WINDOW clause

Quick recap

  • agg OVER (PARTITION BY ... ORDER BY ...) computes per-group without collapsing rows.
  • On ties, ROW_NUMBER never shares a number, RANK leaves gaps, and DENSE_RANK closes them; NTILE deals rows into equal buckets.
  • LAG/LEAD read neighbours (NULL at the edges); FIRST_VALUE works, LAST_VALUE needs a wider frame.
  • Aggregates work as windows too: with ORDER BY you get running totals, and without it each row sees its share of the total.
  • Frames pick the visible rows; ROWS BETWEEN n PRECEDING AND CURRENT ROW is the moving-average shape.
  • WINDOW names a window once and reuses it; window functions evaluate after WHERE/GROUP BY/HAVING, so filter their results one level up.

Checklist

Before Part 8, make sure you can:

  • Put each category's average next to every product without a self-join.
  • Recite the tie behaviour of the three ranking functions.
  • Compute days-between-orders per customer with LAG.
  • Explain the LAST_VALUE trap and both escapes.
  • Build a running total and a share-of-total, and say why the ORDER BY differs.
  • Filter "top 3 by rank" correctly.

Read more: the official window functions tutorial and the window function calls syntax.

Search the guide