Group By Clause in SQL: Unveiling Patterns in Data

Estimated study time: 7 minutes. Turn row-level data into meaningful summaries.

The GROUP BY clause collapses multiple rows sharing a common value into a single summary row, which is what makes aggregate functions like COUNT, SUM, and AVG genuinely useful.

Basic Syntax

SELECT column, AGG_FUNCTION(other_column)
FROM table_name
GROUP BY column;

A Simple Example

To find the total salary paid per department:

SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department;

Grouping by Multiple Columns

You can group by more than one column to get finer-grained summaries:

SELECT Department, JobTitle, COUNT(*) AS HeadCount
FROM Employees
GROUP BY Department, JobTitle;

The Golden Rule

Every column in the SELECT list that isn't wrapped in an aggregate function must appear in the GROUP BY clause. Otherwise, SQL Server will raise an error because it doesn't know which value to show for that column.

Filtering Groups with HAVING

Since WHERE runs before grouping, filtering on an aggregated value needs HAVING instead:

SELECT Department, COUNT(*) AS HeadCount
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
💡 Tip: Query execution order is roughly FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. Knowing this order explains why WHERE can't reference aggregate results but HAVING can.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Data Analytics Course.

Explore Data Analytics Course →