Java Zero to All All questionsPractise free
Interview questions › Databases & Persistence › SQL Mastery & Joins

Explain window functions and how they differ from GROUP BY, with a concrete example.

Level III · MidSQL Mastery & Joins
Short answer

GROUP BY collapses rows into one per group, losing row-level detail, whereas a window function computes an aggregate or ranking 'over' a partition while keeping every row.

Explanation

For example, SELECT name, salary, AVG(salary) OVER (PARTITION BY dept) lets each employee row also show their department average, and ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) ranks within department for top-N queries. This is far cleaner and usually faster than self-joining a grouped subquery, and is the standard tool for running totals (SUM OVER ... ORDER BY) and deduplication.

Common mistakes
  • Saying window functions collapse rows like GROUP BY.
  • Forgetting PARTITION BY and ORDER BY in the OVER clause.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for SQL Mastery & Joins.

Practise free

More on SQL Mastery & Joins