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
- Groups every employee by
DepartmentID. - Counts the number of employees for each group (
COUNT(*)). - 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
SELECTthat isn't inside an aggregate function has to be listed inGROUP BY.
Put simply,
GROUP BYlets you gather rows into groups and compute summary figures for each group.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.