GROUP BY

Introduction

The GROUP BY statement in SQL is used to arrange identical data into groups. It is usually combined with aggregate functions like COUNT, SUM, AVG, MAX, or MIN to perform calculations on each group.

Syntax

SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;
  • column1 – the column you want to group by
  • aggregate_function(column2) – function to calculate on grouped data
  • table_name – the table containing your data
  • WHERE condition – optional filter before grouping

Example 1: Counting Records

Suppose we have a table Employees:

EmployeeIDDepartmentSalary
1HR5000
2IT6000
3HR5500
4IT6200
5Sales4500

We want to count employees in each department:

SELECT Department, COUNT(EmployeeID) AS TotalEmployees
FROM Employees
GROUP BY Department;

Result:

DepartmentTotalEmployees
HR2
IT2
Sales1

Example 2: Sum of Salaries by Department

To find total salary for each department:

SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department;

Result:

DepartmentTotalSalary
HR10500
IT12200
Sales4500

Example 3: Average Salary by Department

To find average salary for each department:

SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;

Result:

DepartmentAverageSalary
HR5250
IT6100
Sales4500

Key Points

  • GROUP BY is always used after WHERE but before ORDER BY
  • All columns in SELECT that are not aggregated must be included in GROUP BY
  • GROUP BY helps summarize data for reports and analysis

Practice Exercise

Using the Employees table, write SQL queries to:

  1. Find the highest salary in each department
  2. Count how many employees earn more than 5000 in each department
  3. Find the average salary of IT department
Home » SQL Foundations Program (SQL-101) > Working with Functions > GROUP BY