Lesson 6: Grouping Data

30 min read Beginner Lesson 6 of 12 11.2k learners

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:

1. What does GROUP BY do?
2. Which clause filters groups after aggregation?
3. Can you group by multiple columns?
4. Which comes first in a query?
5. Which statement is correct?