Compute running totals, rankings, moving averages, and period-over-period changes in SQL without collapsing your rows.
Welcome to Window Functions — the module where your SQL stops summarizing data and starts analyzing it. Until now, whenever you needed a total or an average across groups of rows, you reached for GROUP BY. But GROUP BY collapses your rows: ask for the average salary per department and you lose every individual employee. Window functions remove that limitation. They let you calculate aggregates, rankings, and comparisons across a set of related rows while keeping every original row visible.
This is the toolset behind the questions analysts are asked every day. What is the 7-day rolling average of sales? How does each month compare to the same month last year? Which three products lead each category? How far above or below the department average does this employee’s salary sit? You will answer all of these — and the key that unlocks them is a single new clause, OVER(), that defines a window of rows for each row in your result.
You will start by understanding what a window is and how PARTITION BY splits it into groups. From there you will learn to control exactly which rows a function sees with window frames, then build running totals and moving averages with aggregate window functions. You will rank rows with ROW_NUMBER(), RANK(), DENSE_RANK(), and NTILE(); compare each row to its neighbors with LAG() and LEAD(); reach for the first, last, or nth value in a window; and measure where a value falls in a distribution with CUME_DIST() and PERCENT_RANK().
Every concept is hands-on, with runnable PostgreSQL queries and the exact output you can reproduce. The module closes with a guided project where you act as a data analyst for the classic Northwind database — ranking employees, tracking month-over-month sales growth, finding high-value customers, and surfacing the top products in each category. Start with Lesson 1, where you will meet the OVER() clause and write your first window function.
Data for this module
Engine: PostgreSQL. Lessons 1–6 use small example tables printed inline; the guided project (Lesson 7) uses the classic Northwind database in your local PostgreSQL.
Prefer not to install PostgreSQL for the early lessons? Download window_practice.db and run those examples in any SQLite client — SQLite supports window functions too. Each lesson lists the specific tables it uses.
Complete all 7 lessons to finish the Window Functions module.