GROUP BY
The GROUP BY clause lets you organize rows with matching values into groups.
It’s often used with aggregate functions like COUNT(), SUM(), and AVG() to summarize data by category.
Why Use GROUP BY?
It helps you answer questions such as:
- How many orders were placed in each region?
- What’s the total sales per client?
- What’s the average order value by region?
Basic Syntax
The GROUP BY clause is used after the FROM clause in a SELECT statement.
GROUP BY Syntax
SELECT column_name, AGG_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
You group rows by one or more columns, then use an aggregate function to summarize each group.
Step-by-Step Practice
We will use the clients table, which contains:
| client_id | name | region | sales | orders_count | |
|---|---|---|---|---|---|
| 1 | Client 1 | client1@example.com | Texas | 8041 | 19 |
| 2 | Client 2 | client2@example.com | New York | 8619 | 3 |
| ... | ... | ... | ... | ... | ... |
Count Clients per Region
By using GROUP BY with COUNT(*), we can count how many clients belong to each region.
-- Count how many clients there are in each region
SELECT region, COUNT(*) AS client_count
FROM clients
GROUP BY region;
Total Sales per Region
By using GROUP BY with SUM(sales), we can calculate the total sales for each region.
-- Show total sales in each region
SELECT region, SUM(sales) AS total_sales
FROM clients
GROUP BY region;
Average Sales per Region
By using GROUP BY with AVG(sales), we can calculate the average sales for each region.
-- Show average sales in each region
SELECT region, AVG(sales) AS avg_sales
FROM clients
GROUP BY region;
Key Takeaways
GROUP BYgroups rows that share the same value in one or more columns.- Aggregate functions like
COUNT(),SUM(), andAVG()summarize each group. - Clause order matters in SQL:
SELECTFROMGROUP BYORDER BY(optional — for sorting groups)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.