How does grouping work in SQL?
Grouping in SQL works like this: it combines rows with the same values in the chosen columns into one logical group, and then you can apply aggregate functions to each group.
The mechanism
- SQL takes all rows from the table.
- It compares the values in the columns listed after
GROUP BY. - All rows with matching values get collected into one group.
- For each group, it computes aggregates (
COUNT,SUM,AVG, and so on).
Example
sql
SELECT department, COUNT(*), AVG(salary)
FROM employees
GROUP BY department;- SQL creates a group for each
department, - counts how many employees are in it (
COUNT(*)), - and computes the average salary (
AVG(salary)).
Important
In a query with GROUP BY, the SELECT list can only include:
- the columns being grouped by,
- or aggregate functions.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.