MySQL interview question · Most asked
What are window functions, and give an example where they help.
Summary
Window functions (MySQL 8.0+) compute values across a set of rows related to the current row without collapsing them like GROUP BY: running totals, rankings, moving averages, previous/next values (LAG, LEAD).
Longer Answer
Latest order per customer:
SELECT * FROM (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders o
) t
WHERE rn = 1;
Other uses: SUM(amount) OVER (ORDER BY day) for a running total, RANK() for leaderboards, LAG(value) OVER (...) for day-over-day change. They replace awkward self-joins and correlated subqueries. Window functions run after WHERE and GROUP BY, so filter on their result in an outer query or a CTE.
Key Points
- Aggregate without collapsing rows.
- ROW_NUMBER / RANK / LAG / LEAD / running sums.
- Filter results in an outer query.
- Available from MySQL 8.0.
More most-asked MySQL questions
- What is a clustered index in InnoDB, and why does primary key choice matter so much?
- Why is OFFSET pagination slow on large tables, and what is keyset pagination?
- How do you read EXPLAIN output in MySQL?
- Why might MySQL not use an index you created?
- What are the transaction isolation levels, and which does InnoDB use by default?
- How does a composite index work, and what is the leftmost-prefix rule?
- What causes deadlocks in MySQL, and how do you handle them?
- What are gap locks and next-key locks, and why do they surprise developers?