Question presented to candidate: "What is a window function in SQL? How is it different from a normal aggregate with GROUP BY, and what do PARTITION BY and ORDER BY inside the OVER clause actually do?"
What a strong answer should cover:
- A window function computes a value for each row from a set of related rows (the window) and, unlike
GROUP BY, does not collapse the rows: every input row stays in the result - The
OVER (...)clause defines the window:PARTITION BYsplits rows into groups,ORDER BYorders rows inside each partition, and an optional frame (ROWS/RANGE/GROUPS) picks which rows around the current one are used - The families: ranking (
ROW_NUMBER,RANK,DENSE_RANK,NTILE), offset (LAG,LEAD,FIRST_VALUE), and ordinary aggregates used withOVER(SUM,AVG,COUNT) - Window functions are evaluated after
WHERE,GROUP BYandHAVING, so they cannot be used inWHERE; filter on them in an outer query or CTE - Engine support: PostgreSQL since 8.4, MySQL since 8.0, SQLite since 3.25.0; adding
ORDER BYtoOVERsilently changes an aggregate into a running one
Code / implementation expected: Yes โ a query that shows a per-row value next to a per-group total, and a filter on a window result via a subquery.
Schema used by the examples: