What are SQL window functions, and how would you get the latest row or top value per group?
Answer
A window function calculates across related rows while retaining each row, using an OVER clause with optional PARTITION BY, ORDER BY and frame rules. A common pattern assigns ROW_NUMBER() OVER (PARTITION BY group_key ORDER BY timestamp DESC) and keeps row number one to select the latest row per group. Tests should include ties, duplicate timestamps, NULL ordering, deterministic secondary ordering, empty groups and frame boundaries for running or rolling calculations.
Strong answer includes
- distinguishes windows from collapsing aggregation
- uses partitioning and deterministic ordering
- tests ties, null ordering and frame boundaries
Practical example
Runs against the resettable SQLite sample database used by the playground.
Run the query to see the result.
Window functions calculate across related rows without collapsing them. PARTITION BY restarts the ranking for each customer, and the stable secondary ordering makes ties deterministic.
Expected result: Exactly one newest order per customer with orders.