SQL GROUP BY (original) (raw)

Last Updated : 14 Apr, 2026

The SQL GROUP BY clause is used to arrange identical data into groups based on one or more columns. It is commonly used with aggregate functions like COUNT(), SUM(), AVG(), MAX() and MIN() to perform calculations on each group of data.

fruits_image

**Example: First, we will create a demo SQL database and table, on which we will use the GROUP BY command.

Screenshot-2026-01-27-095959

Employees Table

**Query:

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

**Output:

Screenshot-2026-01-27-100135

**Syntax:

SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2;

Working with GROUP BY

Let's assume that we have a Student table. We will insert some sample data into this table and then perform operations using GROUP BY to understand how it groups rows based on a column and aggregates data.

Screenshot-2026-01-27-100330

Student Table

Example 1: Group By Single Column

When we group by a single column, rows with the same value in that column are combined. For example, grouping by subject shows how many students are enrolled in each subject.

**Query:

SELECT subject, COUNT(*) AS Student_Count
FROM Student
GROUP BY subject;

**Output:

Screenshot-2026-01-27-100415

Example 2: Group By Multiple Columns

Using GROUP BY with multiple columns groups rows that share the same values in those columns. For example, grouping by subject and year will combine rows with the same subject–year pair and we can count how many students fall into each group.

**Query:

SELECT subject, year, COUNT(*)
FROM Student
GROUP BY subject, year;

**Output:

Screenshot-2026-01-27-100503

HAVING Clause in GROUP BY Clause

HAVING clause is used to filter results after grouping, especially when working with aggregate functions like SUM(), COUNT() or AVG(). Unlike WHERE, it applies conditions on grouped data.

Screenshot-2026-01-27-100818

Employees Table

Example 1: Filter by Total Salary

In this query, we group employees by age and display only those whose total salary is greater than 50,000.

SELECT age, SUM(sal) FROM Employees
GROUP BY age
HAVING SUM(sal)>50000;

**Output:

Screenshot-2026-01-27-101544

Example 2: Filter by Average Salary

In this query, we group employees by age and display only those age groups where average salary is above 60,000.

SELECT age, AVG(sal) AS Average_Salary
FROM Employees
GROUP BY age
HAVING AVG(sal) > 60000;

**Output:

Screenshot-2026-01-27-101809