Skip to main content
Practice

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_idnameemailregionsalesorders_count
1Client 1client1@example.comTexas804119
2Client 2client2@example.comNew York86193
..................

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 BY groups rows that share the same value in one or more columns.
  • Aggregate functions like COUNT(), SUM(), and AVG() summarize each group.
  • Clause order matters in SQL:
    1. SELECT
    2. FROM
    3. GROUP BY
    4. ORDER BY (optional — for sorting groups)

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.