This tutorial aims to help you learn about the SQL GROUP BY clause, which is fundamental for organizing and grouping data based on shared attributes.
By the end of this tutorial, you should be able to:
- Understand what the GROUP BY clause is.
- Know how to use the GROUP BY clause to group data.
- Understand how to use aggregate functions with GROUP BY.
Basic knowledge of SQL, including how to write SELECT statements, is required.
The GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Here's a basic syntax of GROUP BY clause:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Imagine we have a table called 'Orders' with the following data:
OrderId | Customer | Amount |
---|---|---|
1 | John | 30 |
2 | Mary | 40 |
3 | John | 20 |
4 | Mary | 50 |
5 | John | 10 |
We want to find the total amount of orders for each customer. We can use the GROUP BY clause to group the orders by the customer and then use the SUM function to calculate the total amount of orders for each.
SELECT Customer, SUM(Amount)
FROM Orders
GROUP BY Customer;
This will output:
Customer | SUM(Amount) |
---|---|
John | 60 |
Mary | 90 |
Now, imagine we have an additional column 'City' in our 'Orders' table:
OrderId | Customer | Amount | City |
---|---|---|---|
1 | John | 30 | London |
2 | Mary | 40 | Berlin |
3 | John | 20 | Berlin |
4 | Mary | 50 | London |
5 | John | 10 | London |
We want to find the total amount of orders for each customer in each city. We can group by both 'Customer' and 'City' columns:
SELECT Customer, City, SUM(Amount)
FROM Orders
GROUP BY Customer, City;
This will output:
Customer | City | SUM(Amount) |
---|---|---|
John | London | 40 |
John | Berlin | 20 |
Mary | London | 50 |
Mary | Berlin | 40 |
In this tutorial, we covered the GROUP BY clause in SQL, which is a crucial tool for organizing identical data into groups. We also looked at how to use aggregate functions with the GROUP BY clause.
To further solidify your understanding, try out these exercises:
SELECT Grade, AVG(Age)
FROM Students
GROUP BY Grade;
SELECT Date, Product, SUM(Amount)
FROM Sales
GROUP BY Date, Product;
Keep practicing different scenarios and using different aggregate functions with the GROUP BY clause to become more comfortable with it.