Advanced SQL

Window functions (ROW_NUMBER, LAG, running sums), CTEs, anti-joins for gap detection, QUALIFY. Deduplication and sessionization in pure SQL are the classic screens.

About 24 min read3-question knowledge check

The mental model

A window function is a **spreadsheet column that can see other rows without merging them**. GROUP BY is a paper shredder: rows go in, one summary row comes out, and the detail is gone. A window function keeps every row and adds a new column computed by looking around — at the previous row, the next row, all rows for the same user, or a sliding 7-day neighbourhood.

The analogy that sticks: a queue at an airport counter. Each passenger (row) keeps their place in line, but you can pin a badge on each one saying "you are 3rd in your airline's queue" (ROW_NUMBER), "the person before you checked in at 09:14" (LAG), or "total bags checked so far in your queue" (running SUM). Nobody leaves the line. Nobody is merged. The badge is derived from a partition (which queue), an order (position in the queue), and a frame (how far up and down the line you may look).

Why this exists: without window functions, "keep the latest record per key" or "start a new session after 30 minutes of silence" forces you into correlated subqueries or self-joins — an O(n²) shape that turns a 1M-row dedup into a query that never finishes, and SQL that nobody can review. Every data engineering screen opens here because dedup, sessionization, retention and rolling metrics are the four problems every pipeline eventually contains, and window functions are the standard, most readable way to express them in one pass in most engines.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision