Window functions

SQL Window Function Interview Questions

A window function does a calculation across a set of related rows while keeping every row in the output: a rank within each group, the previous value, a running total. It answers questions that grouping cannot, which is why it is the most tested advanced SQL topic.

What window function questions ask you to do

Across the questions here, these are the shapes that come up:

  • Return the first, second or most recent row per group
  • Compare each row with the one before it
  • Build a running total or a moving average
  • Show each row against its own group's total
  • Find runs of consecutive days or events

Common mistakes with window functions

ROW_NUMBER, RANK and DENSE_RANK look interchangeable and are not. They differ only when two rows tie. ROW_NUMBER picks one of them and which one is not guaranteed, so the same query can return different rows on different runs. RANK keeps both and skips the next number. DENSE_RANK keeps both without skipping.

Questions to practice

Roles this comes up in

Companies these come from

Other topics