Ranking and Partitioning
- The window idea. A window function computes across related rows WITHOUT collapsing them: every row keeps its identity plus context.
- PARTITION BY. PARTITION BY splits the window into groups: rank within each customer, not across the whole table.
- Ranking functions. ROW_NUMBER, RANK and DENSE_RANK order rows within their partition: top-N per group falls out naturally.
Running and Moving Calculations
- Running totals. SUM OVER an ordered window builds a running total: balances and cumulative revenue in one expression.
- Moving averages. A frame like ROWS BETWEEN 6 PRECEDING AND CURRENT ROW turns SUM and AVG into moving calculations.
- LAG and LEAD. LAG reads the previous row’s value: day-over-day change without a self join.
Advanced Analytical Queries
- Windows plus CTEs. Real analytics layer: aggregate in one CTE, window over it in the next: grain by grain.
- Deduplication pattern. ROW_NUMBER partitioned by the duplicate key, keeping row one, is the standard latest-record-per-entity idiom.
- Sessionisation. Gap-based sessions fall out of LAG plus a running flag: behavioural analytics in pure SQL.
Before and after this level
- Before: Level 5: Subqueries & CTEs: Subqueries, Common Table Expressions, Breaking Complex Queries Into Stages.
- Next: Level 7: Data Modification: INSERT, UPDATE and DELETE, Upserts and Merge Patterns, Safe Data Changes.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does SQL Level 6: Window Functions cover?
Ranking and Partitioning, Running and Moving Calculations, Advanced Analytical Queries: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 5: Subqueries & CTEs, which covers Subqueries, Common Table Expressions, Breaking Complex Queries Into Stages.