Window Partitions, Ranking & Sliding Frames
Compute peer rankings, running totals, neighbour offsets (LAG/LEAD), and moving averages without collapsing individual rows.
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
- 01.
Window functions run after WHERE, GROUP BY, and HAVING — seeing grouped output when GROUP BY is present, else surviving rows.
- 02.
ROW_NUMBER assigns strict 1..N ordinals; RANK leaves tie gaps; DENSE_RANK keeps ranking integers contiguous.
- 03.
ROWS BETWEEN delimits a physical frame (such as 1 PRECEDING AND 1 FOLLOWING) around the active row.
Interactive Module Lab · Window Functions
41. RANK vs DENSE_RANK vs ROW_NUMBER — sqlSELECT 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_rnkFROM users;
SOURCE: USERS
Scanned 10 rows from table 'users'.
| # | id | name | department_id | role | salary | state |
|---|---|---|---|---|---|---|
| 1 | 1 | Alice Smith | 1 | Software Engineer | 95,000 | keep |
| 2 | 2 | Bob Jones | 2 | Product Manager | 110,000 | keep |
| 3 | 3 | Charlie Lee | 1 | Software Engineer | 88,000 | keep |
| 4 | 4 | Diana Prince | 3 | UX Designer | 76,000 | keep |
| 5 | 5 | Evan Wright | 2 | Data Analyst | 82,000 | keep |
| 6 | 6 | Fiona Gallagher | 1 | Tech Lead | 135,000 | keep |
| 7 | 7 | George Clark | NULL | Intern | 42,000 | keep |
| 8 | 8 | Hannah Abbott | 2 | Scrum Master | 89,000 | keep |
Worked Presets in This Module
ROW_NUMBER numbers the rows inside each department by salary. No rows are collapsed.
When rows tie, RANK leaves gaps, DENSE_RANK does not, and ROW_NUMBER always counts 1, 2, 3.
An aggregate with OVER (ORDER BY ...) accumulates row by row instead of collapsing.
LAG peeks at the previous row and LEAD at the next, ideal for comparing consecutive values.
AVG over a partition adds the department average to every row, so you can subtract it right away.