Skip to main content

What does GROUP BY do?

GROUP BY in SQL is used to group rows by one or several columns, so aggregate calculations (e.g. COUNT, SUM, AVG) can be run for each group.

Syntax:

sql
SELECT Column1, AGGREGATE_FUNCTION(Column2) FROM Table_Name GROUP BY Column1;

Example:

sql
SELECT DepartmentID, COUNT(*) AS EmployeeCount FROM Employees GROUP BY DepartmentID;

What this query does

  1. Groups every employee by DepartmentID.
  2. Counts the number of employees for each group (COUNT(*)).
  3. Returns one row per department, with the number of employees in it.

Notes:

  • Grouping can be done by several columns: GROUP BY Column1, Column2.
  • Usually paired with aggregate functions: SUM(), AVG(), MAX(), MIN().
  • Every column in SELECT that isn't inside an aggregate function has to be listed in GROUP BY.

Put simply, GROUP BY lets you gather rows into groups and compute summary figures for each group.

Short Answer

Interview ready
Premium

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