GROUP BY

The GROUP BY clause groups rows that share the same value in one or more columns, so that aggregate functions like COUNT(), SUM(), or AVG() can be applied to each group separately rather than the whole table.

Basic Syntax

SELECT city, COUNT(*) AS total_customers
FROM customers
GROUP BY city;

This returns one row per unique city, with a count of how many customers belong to it.

Grouping with SUM and AVG

-- Total revenue per city
SELECT c.city, SUM(o.amount) AS total_revenue
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.city;

Filtering Groups with HAVING

While WHERE filters individual rows before grouping, HAVING filters entire groups after aggregation:

-- Cities with more than 10 customers
SELECT city, COUNT(*) AS total_customers
FROM customers
GROUP BY city
HAVING COUNT(*) > 10;

You've Completed This Section

This wraps up SQL filtering and aggregation - from basic and advanced WHERE conditions and wildcard pattern matching, through sorting results with ORDER BY, to summarizing data with aggregate functions and GROUP BY. Together, these form the core toolkit for querying and analyzing data stored in relational databases.

A common mistake is using WHERE to filter on an aggregated value - that only works with HAVING, since WHERE runs before the aggregation happens.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course