SQL · Queries that survive scale
How does GROUP BY work?
Short answer
GROUP BY collapses rows that share the same values into one row per group. Every non-aggregated column in the select list must be grouped or functionally dependent on a grouped key.
GROUP BY defines the grain of the result. Each group produces one output row, and aggregate functions compute a single value from all rows in that group.
SELECT department_id,
COUNT(*) AS employee_count,
AVG(salary) AS average_salary
FROM employees
WHERE active = true
GROUP BY department_id
ORDER BY average_salary DESC;Rules that catch people out
- A select column that is not aggregated must appear in GROUP BY
- Grouping by a unique key allows selecting other columns in many engines
- GROUP BY runs after WHERE and before HAVING
- NULL values form their own group unless filtered out
- Grouping by an expression requires repeating it or using a positional column
Grouping is often the expensive part of a query because it needs a hash table or sorted input. Filtering early in WHERE and indexing the grouping columns can reduce the work.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why must non-aggregated columns appear in GROUP BY?
- 2How are NULL values handled by GROUP BY?
- 3What is the difference between GROUP BY and DISTINCT?
- 4How can an index help a GROUP BY query?
Say it in the interview
GROUP BY collapses rows that share the same key values into one row per group. Then aggregates compute values for each group. Every column in the select list has to be grouped or functionally dependent on a grouped key. I filter rows in WHERE before grouping, and I avoid grouping by unnecessary high-cardinality columns because that increases memory and sort work.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.