Skip to main content

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

  1. SQL takes all rows from the table.
  2. It compares the values in the columns listed after GROUP BY.
  3. All rows with matching values get collected into one group.
  4. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.