Skip to the page

Joining and aggregating · mid

Window functions

A window function computes a value over a set of related rows (the window, defined by OVER (PARTITION BY ... ORDER BY ...)) without collapsing them, which gives rankings, running totals, top-N per group and comparisons with the previous row.

The notes

What you must know

  • ROW_NUMBER(): 1, 2, 3... with no ties. RANK(): ties share a rank and leave gaps (1, 1, 3). DENSE_RANK(): ties share, no gaps (1, 1, 2).
  • PARTITION BY restarts the calculation per group (per department, per city); ORDER BY inside OVER sets the order within the window.
  • Running totals: SUM(amount) OVER (ORDER BY created_at). Moving averages: AVG(x) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).
  • LAG(col) / LEAD(col): the previous / next row's value (day-over-day change, gaps between events).
  • Top N per group: compute ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) in a CTE or subquery, then filter WHERE rn <= 3 outside (window functions cannot be used in WHERE directly).
  • Unlike GROUP BY, every input row stays in the result.

The red pen

Common traps: mistake → fix

  • Mistake: Filter with WHERE ROW_NUMBER() OVER (...) = 1

    Fix: window functions run after WHERE; wrap them in a CTE or subquery.

  • Mistake: RANK and DENSE_RANK are the same

    Fix: RANK leaves gaps after ties; 'second highest' usually needs DENSE_RANK.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a window function? How is it different from GROUP BY?
  2. ROW_NUMBER vs RANK vs DENSE_RANK?
  3. Find the top 3 earners in each department.
  4. Compute a running total of daily revenue and the change from the previous day.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview