GROUP BY — Group Rows and Aggregate Data
The GROUP BY clause allows you to group rows that have the same values in one or more columns.
It is used together with aggregate functions (like COUNT(), SUM(), AVG(), etc.) to summarize data.
Note: We will learn about some of these functions (like sum, avg) in the upcoming chapters
Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Example 1: Count of Employees per Department
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
This returns the number of employees in each department.
Example 2: Average Age per Department
SELECT department, AVG(age)
FROM employees
GROUP BY department;
This returns the average age of employees for each department.
Tip
-
Every column in your
SELECTlist must either be in theGROUP BYclause or used in an aggregate function. -
Common aggregate functions:
COUNT()SUM()AVG()MIN()MAX()
The GROUP BY clause helps you explore and summarize your data — very useful for reports, dashboards, and analytics!