What are SQL window functions and when have you used them?
What the interviewer wants to hear
- Compute across related rows without collapsing them like GROUP BY
- PARTITION BY and ORDER BY inside OVER
- Ranking: ROW_NUMBER, RANK, DENSE_RANK
- Running totals and moving averages
- LAG and LEAD for comparing with previous rows
Model answer
Window functions calculate a value across a set of related rows while still keeping each row, unlike GROUP BY which collapses rows. The OVER clause defines the window, with PARTITION BY to split groups and ORDER BY to set order. I use ROW_NUMBER to get the latest record per customer, for example to remove duplicates or find each user's first purchase. I use RANK or DENSE_RANK for top N products per category, choosing based on how ties should be handled. For trends, SUM OVER with ORDER BY gives running totals, and AVG over the last 7 rows gives a 7-day moving average. LAG and LEAD let me compare each month with the previous month to compute month-over-month growth without a self join. They make queries shorter and usually faster than equivalent subqueries.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Data Analyst questions
- Daily orders dropped 20% yesterday. Walk me through how you would investigate.
- The product team wants to test a new checkout button. How would you design the A/B test?
- How would you choose the key metrics for a food delivery app?
- When would you use Excel, SQL or Python for an analysis task?
- What is cohort analysis and when would you use it instead of looking at overall totals?
- Three managers send you urgent data requests on the same morning. How do you decide what to do first?
- Checkout conversion has fallen. How would you analyse the funnel to find where users are dropping off?
- How do you decide what to do with outliers in your data?
- How would you design the data model for a new Power BI sales report?