Reading Room · Module 08
Track 0/9 (0%)
Course completion
Module 08 · Windowing~26 min · 7 worked queries

Window Partitions, Ranking & Sliding Frames

Compute peer rankings, running totals, neighbour offsets (LAG/LEAD), and moving averages without collapsing individual rows.

Trace Live in StudioAll Modules
Core Relational Rule
Unlike GROUP BY, OVER (PARTITION BY ... ORDER BY ...) keeps every row intact while computing peer or frame values alongside it.Module 08 · Windowing · Reading Room

Mental Model

  1. 01.

    Window functions run after WHERE, GROUP BY, and HAVING — seeing grouped output when GROUP BY is present, else surviving rows.

  2. 02.

    ROW_NUMBER assigns strict 1..N ordinals; RANK leaves tie gaps; DENSE_RANK keeps ranking integers contiguous.

  3. 03.

    ROWS BETWEEN delimits a physical frame (such as 1 PRECEDING AND 1 FOLLOWING) around the active row.

Frequent Pitfall to Avoid
Assuming ORDER BY inside OVER defaults to ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when RANGE handles ties differently.

Interactive Module Lab · Window Functions

41. RANK vs DENSE_RANK vs ROW_NUMBER — sql
SELECT name, country,
ROW_NUMBER() OVER (ORDER BY country) AS row_num,
RANK() OVER (ORDER BY country) AS rnk,
DENSE_RANK() OVER (ORDER BY country) AS dense_rnk
FROM users;
Execution Stages3 steps
Stage 01 · FROM

SOURCE: USERS

10 in → 10 out

Scanned 10 rows from table 'users'.

#idnamedepartment_idrolesalarystate
11Alice Smith1Software Engineer95,000keep
22Bob Jones2Product Manager110,000keep
33Charlie Lee1Software Engineer88,000keep
44Diana Prince3UX Designer76,000keep
55Evan Wright2Data Analyst82,000keep
66Fiona Gallagher1Tech Lead135,000keep
77George ClarkNULLIntern42,000keep
88Hannah Abbott2Scrum Master89,000keep
Inspect each evaluated clause in 41. RANK vs DENSE_RANK vs ROW_NUMBER or animate every row moving between stages in Studio.Open 41. RANK vs DENSE_RANK vs ROW_NUMBER in Studio →

Worked Presets in This Module

40. Analytical Window Functions

ROW_NUMBER numbers the rows inside each department by salary. No rows are collapsed.

41. RANK vs DENSE_RANK vs ROW_NUMBER

When rows tie, RANK leaves gaps, DENSE_RANK does not, and ROW_NUMBER always counts 1, 2, 3.

42. Running total

An aggregate with OVER (ORDER BY ...) accumulates row by row instead of collapsing.

43. LAG and LEAD: look at neighbours

LAG peeks at the previous row and LEAD at the next, ideal for comparing consecutive values.

44. Compare each row to its group

AVG over a partition adds the department average to every row, so you can subtract it right away.

45. Top earner per department

You cannot filter on a window function directly, so rank inside a subquery and filter outside.

46. Moving average with a frame

ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING averages each row with its two neighbours.

Navigation

LivePreparation

Client-side workspace · saved locally