typestar

Analytics & reporting

24 steps in 5 sets of SQL.

The tools for questions that do not fit in a single flat query. Subqueries, then common table expressions including recursive ones, then window functions.

Window functions are the centerpiece and the thing most people learn last and wish they had learned first: ranking, running totals, lag and lead, and frames. Twenty-four steps.

Start this tour

Subqueries

  • Subquery in WHEREA subquery computes the list of values the outer filter matches against.
  • Scalar subqueryA subquery that returns one value can stand in for a column or a constant.
  • EXISTS and NOT EXISTSEXISTS asks whether any matching row exists, and stops at the first one.

Common table expressions

  • Common table expressionWITH names a result set up front so the main query reads like prose.
  • Chained CTEsSeveral CTEs, comma separated, each free to build on the one before.
  • Recursive CTEA recursive CTE walks a hierarchy or generates a series.

Window functions

Expressions

Encore

The other SQL tours