Lesson 6: Grouping Data
What is GROUP BY?
The GROUP BY
clause groups rows that have the same values in specified columns into summary rows. It is commonly used with aggregate functions like COUNT
, SUM
, AVG
, MIN
, and MAX
.
SQL
SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city;
Grouping by Multiple Columns
You can group by more than one column by listing them separated by commas.
SQL
SELECT region, city, COUNT(*) AS customer_count
FROM customers
GROUP BY region, city;
Filtering Groups with HAVING
The HAVING
clause filters groups after aggregation. It works like WHERE
, but on grouped data.
SQL
SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city
HAVING COUNT(*) > 10;
Practice Quiz
Test your understanding of GROUP BY and HAVING: