SQL - GROUP BY Clause in SQL
What Is the GROUP BY Clause in SQL?
The GROUP BY clause in SQL is used to group rows that have the same values in specified columns and perform aggregate functions (like SUM, AVG, COUNT, etc.) on each group.
Why Use GROUP BY?
-
To summarize data.
-
To get totals or averages per category, like:
-
Total sales per product
-
Number of employees per department
-
Average grade per student
-
Syntax
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
Example: Total Sales per Product
Sample Table: sales
product | quantity | price |
---|---|---|
Apple | 10 | 2 |
Banana | 5 | 1 |
Apple | 8 | 2 |
Banana | 12 | 1 |
Orange | 7 | 3 |
Query
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;
Result
product | total_quantity |
---|---|
Apple | 18 |
Banana | 17 |
Orange | 7 |
-
This groups the rows by product, and calculates the total quantity for each.
Common Aggregate Functions Used with GROUP BY
-
SUM() – total
-
AVG() – average
-
COUNT() – number of rows
-
MAX() – highest value
-
MIN() – lowest value
More Complex Example: Average Price per Product
SELECT product, AVG(price) AS average_price
FROM sales
GROUP BY product;