SQL & Relational Database Mastery · Chapter 7 · ~15 min · Advanced
Window Functions Demystified: Partitions, Rankings & Offsets
Calculate analytical metrics without collapsing rows using OVER(), PARTITION BY, ROW_NUMBER(), RANK(), DENSE_RANK(), and LAG()/LEAD().
- Understand how window functions perform analytical calculations without collapsing input rows
- Master the OVER() clause: partitioning groups and establishing calculation order
- Distinguish tie-breaking behaviors among ROW_NUMBER(), RANK(), and DENSE_RANK()
- Compare previous and upcoming time-series events using LAG() and LEAD() offsets
Window Functions Demystified: Partitions & Rankings: learn it visually
Calculate analytical metrics without collapsing rows using OVER(), PARTITION BY, ROW_NUMBER(), RANK(), DENSE_RANK(), and LAG()/LEAD().
1Intuition: Calculating Metrics Across Windows
Before SQL window functions (introduced in SQL:2003), computing an employee's rank or comparing a day's revenue with the previous day required slow, convoluted self-joins or nested queries.
Window functions change the game by providing a sliding calculation frame — a "window" — over the dataset while leaving every individual row completely intact.
PARTITION BY
Divides rows into separate groups (like department or region). The calculation resets every time the partition boundary is crossed.
ORDER BY
Establishes the chronological or ordinal sequence of rows within each partition, which is vital for rankings and running totals.
Frame Specification
Defines the exact sliding subset of rows to include (e.g. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).
Why does standard SQL prohibit referencing window functions directly in a WHERE clause (e.g. 'WHERE ROW_NUMBER() OVER (...) <= 5')?
2Architecture: Ranking Functions and Offset Navigation
Selecting the wrong ranking function is one of the most common causes of silent production bugs in leaderboards and top-N reporting. Study the 3 core mental models below:
Wrong idea: Window functions collapse rows just like GROUP BY
Expecting 'SUM(sales) OVER ()' to collapse 100 transaction rows into 1 summary row. Developers write awkward joins because they assume window functions reduce row counts.
Real system: Window functions preserve 100% of input rows while appending metrics
Every input row retains its unique identity and columns. The window calculation computes over a specified frame and appends the scalar result as a new column to every row.
-- Canonical Top-N Pattern using CTE + DENSE_RANK()
WITH ranked_employees AS (
SELECT
department_id,
employee_id,
name,
salary,
-- Deterministic dense rank per department
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS salary_tier,
-- Prior colleague's salary for pay equity comparison
LAG(salary, 1, salary) OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS higher_salary
FROM employees
)
SELECT *
FROM ranked_employees
WHERE salary_tier <= 3
ORDER BY department_id, salary_tier;Four students score 100, 95, 95, and 90. What values does DENSE_RANK() OVER (ORDER BY score DESC) assign to these students?
3Interactive Visual: Window Ranking & Offset Simulator
Toggle between global and partitioned views, switch ranking algorithms, and enable LAG() offsets to see how identical datasets produce radically different rank allocations.
Live Window Function Ranking & Offset Inspector
| ID | Name | Dept | Salary | Computed Rank | LAG(salary, 1) | Salary Delta |
|---|---|---|---|---|---|---|
| #101 | Alice | Engineering | $150,000 | #1 | NULL (first row) | — |
| #102 | Bob | Engineering | $120,000 | #2 (tie) | $150,000 | -$30,000 |
| #103 | Charlie | Engineering | $120,000 | #2 (tie) | $120,000 | $0 (same) |
| #104 | Diana | Engineering | $95,000 | #3 | $120,000 | -$25,000 |
| #201 | Evan | Sales | $140,000 | #1 | NULL (first row) | — |
| #202 | Fiona | Sales | $110,000 | #2 (tie) | $140,000 | -$30,000 |
| #203 | George | Sales | $110,000 | #2 (tie) | $110,000 | $0 (same) |
| #204 | Hannah | Sales | $85,000 | #3 | $110,000 | -$25,000 |
What does LAG(revenue, 1, 0) OVER (ORDER BY quarter) return for the very first row of a partition?
4Bug Hunt: Month-Over-Month Growth & Top-3 Filter
A quarterly analytics job failed with runtime errors. The author attempted to place a window function inside the WHERE clause and forgot to specify chronological ordering for LAG(). Fix the query by wrapping it in a CTE.
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
• Wrap the main query inside WITH ranked_sales AS (...)
• Specify LAG(revenue, 1) OVER (PARTITION BY region ORDER BY month)
• Filter WHERE rev_rank <= 3 in the outer query
What happens to the running calculation of a window function when crossing from one PARTITION BY group into the next?
5Recap & Window Function Checklist
- Row Preservation: Window functions never collapse rows. They compute across a subset while maintaining full row-level details.
- Execution Order: Window functions run after
WHERE,GROUP BY, andHAVING. They cannot be placed in theWHEREclause; use a CTE or subquery to filter on their outputs. - Deterministic Rankings: Use
DENSE_RANK()for clean tiers with ties,RANK()for Olympic-style gap rankings, andROW_NUMBER()only when strictly unique sequential IDs are required. - Offsets with LAG & LEAD: Always supply an explicit
ORDER BYclause to ensure deterministic preceding and following record retrieval.
Ready for Chapter 8 (Running Totals & Moving Averages)? Mark as complete: