skip to content
04, 11 chapters
windows, grouping and recursion
everything.analytics

windows, grouping and recursion

the queries that make spreadsheets jealous. window functions, grouping sets and recursive CTEs.

start part 04part 04 of 18, 11 chapters
  1. 04.01FILTER and pivotingcount(*) FILTER (WHERE ...), the SUM(CASE ...) it replaced, and rows turned into columns.
  2. 04.02ROLLUP, CUBE and GROUPING SETSsubtotals and a grand total in one query, and GROUPING() to tell their NULLs from yours.
  3. 04.03percentiles, medians and string_aggaggregates that care about order: WITHIN GROUP, percentile_cont vs percentile_disc, and ordered string_agg.
  4. 04.04window functionsaggregates that don't collapse rows. OVER, PARTITION BY, and where windows sit in the logical order.
  5. 04.05row_number, rank and dense_rankthree ways to number rows. they only disagree on ties, which is exactly when it matters.
  6. 04.06LAG, LEAD and running totalsthe previous row, the next row, and a sum of every row so far.
  7. 04.07window framesROWS, RANGE and GROUPS. the default frame that makes last_value look broken.
  8. 04.08top n per groupthe three best sellers in every category: row_number, LATERAL and DISTINCT ON, compared on one plan.
  9. 04.09gaps and islandsstreaks, sessions and missing days. the row_number subtraction trick, stepped through.
  10. 04.10recursive CTEsa query that feeds on its own output. walking an org chart, depth first or breadth first, with CYCLE for loops.
  11. 04.11generate_series and calendarsrows from nothing: date spines, filling gaps with zeros, and fake data that's the same every run.