Advanced SQL and window functions
Keep each record, then add the context around it. We will use seven small events to understand rankings, running totals, comparisons and groups, one step at a time.
Complete Module 5: SQL fundamentals, especially grouping, NULL and CTEs. No account is needed to follow the explanations. SQL is illustrated, not executed here.
Ten lessons with worked results
Predict the result, follow the diagram, then compare the SQL and output table. The examples deliberately contain ties, a date gap, a zero and an unknown amount.
Window functions: keep the rows, add context
Explain OVER, PARTITION BY and window ordering while preserving individual records.
Explore lesson ↗Lesson 02 · 24 minROW_NUMBER, RANK and DENSE_RANK
Choose a ranking function according to how ties should behave.
Explore lesson ↗Lesson 03 · 24 minQUALIFY, latest records and deduplication
Filter window results and define a deterministic winner without deleting source records.
Explore lesson ↗Lesson 04 · 24 minWindow frames: ROWS versus RANGE
Choose the subset used by a window calculation and explain how tied ordering values change a frame.
Explore lesson ↗Lesson 05 · 24 minRunning totals and moving averages
Build cumulative and sliding calculations while distinguishing event counts from calendar time.
Explore lesson ↗Lesson 06 · 24 minLAG, LEAD and changes over time
Compare a record with its ordered neighbors without assuming that a previous record means yesterday.
Explore lesson ↗Lesson 07 · 24 minFIRST_VALUE, LAST_VALUE and NTH_VALUE
Choose a position inside an explicit frame and distinguish the final record from the last known value.
Explore lesson ↗Lesson 08 · 24 minNTILE, distribution ranks and percentage shares
Distinguish equal-count buckets, relative rank and contribution to a total.
Explore lesson ↗Lesson 09 · 24 minSubqueries, EXISTS and staged calculations
Use named stages and existence checks to express an advanced question without multiplying records.
Explore lesson ↗Lesson 10 · 24 minActivity groups: put the window ideas together
Build a small gaps-and-islands pattern using LAG, a boundary flag and a running sum.
Explore lesson ↗Ask four questions for every window.
Which rows belong together? What is their order? Which frame contributes? Which records should remain afterward? These questions make long SQL expressions easier to understand.
Explore window-function diagrams →