Paramclasses Academy - Blog

Tutorials Details

←
Post 18 of 40
→

SQL GROUP BY and HAVING Clauses in SQL Server: Practical Examples for Beginners

SQL GROUP BY and HAVING Clauses in SQL Server: Practical Examples for Beginners

November 17, 2026

SQL GROUP BY and HAVING Clauses in SQL Server: Practical Examples for Beginners

When working with databases, developers often need to organize records into groups and calculate useful information from those groups. For example, a company may want to calculate the total salary of each department, count the number of employees in every department, or find departments where the average salary is greater than a specific amount.

Microsoft SQL Server provides the GROUP BY and HAVING clauses to perform these tasks efficiently.

The GROUP BY clause groups rows that have the same values in specified columns, while the HAVING clause filters the grouped results based on a condition.

In this tutorial by Param Classes, you will learn how GROUP BY and HAVING work in SQL Server, understand their syntax, explore the difference between WHERE and HAVING, and practise real-world queries using employee and department data.

1. What Is GROUP BY in SQL Server?

The GROUP BY clause is used to arrange rows into groups based on one or more columns that contain the same values.

It is commonly used with aggregate functions such as:

  • COUNT() – Counts records.

  • SUM() – Calculates the total.

  • AVG() – Calculates the average.

  • MIN() – Finds the minimum value.

  • MAX() – Finds the maximum value.

For example, suppose a company has an Employees table containing employee names, department names, and salaries.

EmployeeID EmployeeName Department Salary
1 Rahul IT 40000
2 Priya HR 35000
3 Amit IT 45000
4 Neha HR 30000
5 Rohit Sales 38000
6 Anjali IT 50000

If you want to calculate the total salary of each department, you can use GROUP BY.

GROUP BY Syntax

SELECT
    column_name,
    AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;

Important: Every selected column that is not inside an aggregate function must normally be included in the GROUP BY clause.

2. Create a Sample Employees Table

Let's create a sample table to understand GROUP BY and HAVING with practical SQL queries.

Step 1: Create the Table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(50),
    Department VARCHAR(50),
    Salary DECIMAL(10,2)
);

Step 2: Insert Sample Records

INSERT INTO Employees
(EmployeeID, EmployeeName, Department, Salary)
VALUES
(1, 'Rahul', 'IT', 40000),
(2, 'Priya', 'HR', 35000),
(3, 'Amit', 'IT', 45000),
(4, 'Neha', 'HR', 30000),
(5, 'Rohit', 'Sales', 38000),
(6, 'Anjali', 'IT', 50000),
(7, 'Karan', 'Sales', 42000),
(8, 'Pooja', 'Finance', 36000);

Step 3: Display All Records

SELECT *
FROM Employees;

Now we have employee records from four departments: IT, HR, Sales, and Finance.

3. GROUP BY with COUNT() Function

The COUNT() function counts the number of records in each group.

Suppose you want to find how many employees work in each department.

SQL Query

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

Expected Output

Department TotalEmployees
Finance 1
HR 2
IT 3
Sales 2

Explanation:

  1. SELECT Department displays the department name.

  2. COUNT(*) counts the records in each department.

  3. FROM Employees specifies the source table.

  4. GROUP BY Department creates one group for each department.

Result: The query displays the total number of employees in every department.

4. GROUP BY with SUM() Function

The SUM() function calculates the total of numeric values in each group.

For example, a company may want to calculate the total salary paid to employees in every department.

SQL Query

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

Expected Output

Department TotalSalary
Finance 36000
HR 65000
IT 135000
Sales 80000

Explanation:

  • SQL Server groups employees by Department.

  • SUM(Salary) adds the salaries of employees in each group.

  • TotalSalary displays the calculated salary amount.

Real-world example: A company can use this query to prepare department-wise salary reports.

5. GROUP BY with AVG() Function

The AVG() function calculates the average of numeric values within each group.

Suppose you want to find the average salary of employees in every department.

SQL Query

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

Expected Output

Department AverageSalary
Finance 36000.00
HR 32500.00
IT 45000.00
Sales 40000.00

Explanation:

SQL Server calculates the average salary separately for each department.

For example, the IT department has three employees:

  • Rahul: 40000

  • Amit: 45000

  • Anjali: 50000

Average salary:

(40000 + 45000 + 50000) / 3 = 45000

6. GROUP BY with Multiple Columns

SQL Server also allows you to group records using more than one column.

For example, suppose a company wants to calculate the number of employees according to both Department and Salary.

SQL Query

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

Explanation

In this query:

  • Department is the first grouping column.

  • Salary is the second grouping column.

  • COUNT(*) counts employees for each unique Department and Salary combination.

Important: When multiple columns are used in GROUP BY, SQL Server creates groups based on the combination of their values.

7. GROUP BY with ORDER BY

You can combine GROUP BY with ORDER BY to sort grouped results.

For example, suppose you want to display departments according to their total salary in descending order.

SQL Query

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

Expected Output

Department TotalSalary
IT 135000
Sales 80000
HR 65000
Finance 36000

Explanation:

  • GROUP BY creates department-wise groups.

  • SUM() calculates the total salary.

  • ORDER BY TotalSalary DESC sorts the highest total first.

8. What Is HAVING in SQL Server?

The HAVING clause is used to filter grouped results based on a condition.

It is commonly used with GROUP BY and aggregate functions.

For example, suppose you want to display only those departments that have more than two employees.

You can use HAVING with COUNT().

HAVING Syntax

SELECT
    column_name,
    AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;

Example: Find Departments with More Than Two Employees

SELECT
    Department,
    COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 2;

Expected Output

Department TotalEmployees
IT 3

Explanation:

  1. GROUP BY groups employees according to their department.

  2. COUNT(*) calculates the number of employees in each group.

  3. HAVING COUNT(*) > 2 keeps only groups containing more than two employees.

Important: HAVING filters groups after grouping and aggregation, rather than filtering individual source rows like WHERE.

9. HAVING with SUM() Function

You can use HAVING with SUM() to filter groups according to their total values.

Suppose you want to find departments whose total salary is greater than 70000.

SQL Query

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

Expected Output

Department TotalSalary
IT 135000
Sales 80000

Explanation:

  • SQL Server groups employees by department.

  • SUM(Salary) calculates the total salary for each department.

  • HAVING filters out departments whose total salary is 70000 or less.

10. HAVING with AVG() Function

The HAVING clause can also filter groups based on average values.

For example, suppose you want to find departments where the average employee salary is greater than 35000.

SQL Query

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

Expected Output

Department AverageSalary
IT 45000.00
Sales 40000.00
Finance 36000.00

Explanation: SQL Server calculates the average salary for each department and returns only the departments whose average salary exceeds 35000.

11. Difference Between WHERE and HAVING

Both WHERE and HAVING are used to filter data, but they work at different stages of query processing.

WHERE HAVING
Filters individual rows Filters grouped results
Applied before GROUP BY Applied after grouping
Commonly used with ordinary column conditions Commonly used with aggregate conditions
Does not directly filter aggregate results Can filter using COUNT(), SUM(), AVG(), etc.

Example Using WHERE

Find employees whose salary is greater than 35000, then calculate the employee count for each department.

SELECT
    Department,
    COUNT(*) AS TotalEmployees
FROM Employees
WHERE Salary > 35000
GROUP BY Department;

Here, WHERE removes employees whose salary is 35000 or less before grouping.

Example Using HAVING

Find departments that have more than one employee.

SELECT
    Department,
    COUNT(*) AS TotalEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 1;

Here, HAVING filters the department groups after COUNT() is calculated.

Using WHERE and HAVING Together

You can use both clauses in the same query.

SELECT
    Department,
    COUNT(*) AS TotalEmployees,
    AVG(Salary) AS AverageSalary
FROM Employees
WHERE Salary > 30000
GROUP BY Department
HAVING COUNT(*) >= 2;

How this query works:

  1. WHERE filters employees whose salary is greater than 30000.

  2. GROUP BY creates department-wise groups from the remaining records.

  3. COUNT(*) counts employees in each group.

  4. AVG(Salary) calculates the average salary.

  5. HAVING keeps groups containing at least two qualifying employees.

Remember: WHERE filters rows; HAVING filters groups.

12. HAVING with Multiple Conditions

You can combine multiple conditions in HAVING using AND and OR.

Example Using AND

Find departments having more than one employee and an average salary greater than 35000.

SELECT
    Department,
    COUNT(*) AS TotalEmployees,
    AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 1
AND AVG(Salary) > 35000;

Example Using OR

Find departments having more than two employees or a total salary greater than 70000.

SELECT
    Department,
    COUNT(*) AS TotalEmployees,
    SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 2
OR SUM(Salary) > 70000;

These conditions help create more specific reports from grouped database records.

13. Real-World Example: Department-Wise Employee Report

Suppose a company wants to generate a report containing:

  • Department name

  • Total employees

  • Total salary

  • Average salary

  • Only departments having at least two employees

  • Highest total salary departments displayed first

Complete SQL Query

SELECT
    Department,
    COUNT(*) AS TotalEmployees,
    SUM(Salary) AS TotalSalary,
    AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING COUNT(*) >= 2
ORDER BY TotalSalary DESC;

Expected Output

Department TotalEmployees TotalSalary AverageSalary
IT 3 135000 45000
Sales 2 80000 40000
HR 2 65000 32500

What makes this query useful?

It combines GROUP BY, aggregate functions, HAVING, and ORDER BY to create a meaningful department-wise report.

This type of report is commonly used in employee management systems, payroll applications, and business reporting dashboards.

14. Common Mistakes to Avoid

  1. Missing GROUP BY: When selecting a normal column together with an aggregate function, include the non-aggregated column in GROUP BY.

  2. Using WHERE for aggregate filtering: Use HAVING when filtering groups using aggregate results.

  3. Confusing WHERE and HAVING: WHERE filters rows before grouping; HAVING filters groups.

  4. Grouping by the wrong column: Always choose columns that represent the grouping you need.

  5. Forgetting ORDER BY: Grouped results are not guaranteed to appear in a particular order unless you specify sorting.

  6. Using aggregate functions incorrectly: Make sure aggregate expressions are written correctly in SELECT and HAVING.

  7. Assuming GROUP BY automatically sorts results: GROUP BY creates groups; use ORDER BY when you need a defined output order.

15. Practice Questions

Use the Employees table created in this tutorial and try the following exercises:

  1. Write a query to count the total number of employees in each department.

  2. Calculate the total salary paid by each department.

  3. Find the average salary of every department.

  4. Display departments having more than one employee using HAVING.

  5. Find departments whose total salary is greater than 70000.

  6. Display departments where the average salary is greater than 35000.

  7. Use WHERE to select employees earning more than 35000 before grouping.

  8. Use WHERE and HAVING together in one query.

  9. Group employees using both Department and Salary.

  10. Sort department-wise total salaries in descending order.

16. Frequently Asked Questions (FAQs)

Q1. What is GROUP BY in SQL Server?

GROUP BY is used to group rows having the same values in one or more columns. It is commonly used with aggregate functions.

Q2. What is HAVING in SQL Server?

HAVING filters grouped results based on specified conditions, often using aggregate functions such as COUNT(), SUM(), and AVG().

Q3. What is the main difference between WHERE and HAVING?

WHERE filters individual rows before grouping, whereas HAVING filters groups after GROUP BY has been applied.

Q4. Can we use GROUP BY without aggregate functions?

Yes. GROUP BY can be used to return distinct combinations of grouped column values, although SELECT DISTINCT is often more suitable when simple duplicate removal is the goal.

Q5. Can we use multiple columns in GROUP BY?

Yes. You can group records using two or more columns. SQL Server groups rows based on the combination of their values.

Q6. Can we use HAVING without GROUP BY?

Yes. HAVING can be used in an aggregate query without an explicit GROUP BY. In that case, the query treats the result as one group.

Q7. Can GROUP BY and ORDER BY be used together?

Yes. GROUP BY creates groups, while ORDER BY sorts the resulting rows.

Q8. Which aggregate functions are commonly used with GROUP BY?

COUNT(), SUM(), AVG(), MIN(), and MAX() are commonly used with GROUP BY.

17. Conclusion

In this tutorial, we learned how GROUP BY and HAVING work in Microsoft SQL Server and how they help organize and filter grouped database records.

We explored GROUP BY with COUNT(), SUM(), and AVG(), used multiple grouping columns, sorted grouped results with ORDER BY, and applied HAVING conditions to filter groups. We also understood the important difference between WHERE and HAVING and combined both clauses in practical SQL queries.

These concepts are essential for generating department-wise reports, calculating totals, analysing employee information, and building database-driven applications.

At Param Classes, we focus on teaching SQL Server through structured lessons, clear explanations, and practical examples. Practise these queries in SQL Server Management Studio (SSMS) to strengthen your SQL skills and prepare for real-world database development.

Keep learning SQL Server step by step with Param Classes!</WritingBlock}

3. Reference Images

These are three existing visual references related to SQL GROUP BY and HAVING.

<box gap={3}> <row align=start gap={3}> <AsyncImage query="SQL Server GROUP BY COUNT department SQL query results SSMS screenshot" aspectRatio="16:9" maxWidth="48%"/> <box flex="1" gap={1}> **Image 1: GROUP BY with COUNT()**

  <text color="secondary" size="sm">Grouping employee records and counting employees department-wise.</text>
</box>

</row> <divider color="subtle"/> <row align=start gap={3}> <AsyncImage query="SQL Server GROUP BY SUM AVG aggregate functions query results screenshot" aspectRatio="16:9" maxWidth="48%"/> <box flex="1" gap={1}> **Image 2: GROUP BY with SUM() and AVG()**

  <text color="secondary" size="sm">Calculating department-wise total and average salary.</text>
</box>

</row> <divider color="subtle"/> <row align=start gap={3}> <AsyncImage query="SQL Server HAVING clause GROUP BY query editor results screenshot" aspectRatio="16:9" maxWidth="48%"/> <box flex="1" gap={1}> **Image 3: HAVING Clause**

  <text color="secondary" size="sm">Filtering grouped records using aggregate conditions.</text>
</box>

</row> </box>

4. Google Flow Thumbnail Prompt

<WritingBlock id="86242" variant="standard">Create a premium, ultra-professional 16:9 YouTube tutorial thumbnail in 4K resolution (3840 × 2160) for a Microsoft SQL Server GROUP BY and HAVING tutorial.

Main headline — very large and bold:

SQL GROUP BY & HAVING

Secondary headline:

MASTER SQL GROUPING

Visual concept:

Show a realistic SQL Server Management Studio query editor on a large computer monitor. Display a SQL query using GROUP BY, COUNT(), SUM(), and HAVING.

On one side, show multiple employee data rows visually combining into department-wise groups. On the other side, show a clean results grid displaying Department, TotalEmployees, and TotalSalary.

Add glowing grouping lines connecting similar records, with a highlighted filter effect representing the HAVING clause. Include a premium 3D database cylinder and subtle SQL code elements in the background.

Design style:

  • Premium dark navy and electric blue technology theme.

  • Bright cyan highlights for grouped data and aggregate results.

  • Cinematic lighting and realistic 3D depth.

  • Professional database developer training aesthetic.

  • Strong contrast and clean typography.

  • Large, bold, readable headline text.

  • Balanced composition with minimal clutter.

  • Make GROUP BY and HAVING immediately recognizable.

  • Avoid cartoon illustrations and unnecessary small text.

Param Classes logo instructions:

I will upload the official Param Classes logo separately. Use that exact uploaded logo without modification. Do not redraw, recreate, crop, stretch, distort, recolor, rotate, or change its typography. Preserve its original colors, proportions, and design. Place it neatly in a suitable corner with sufficient clear space.

Final output:

Create an eye-catching, professional SQL Server tutorial thumbnail that clearly communicates grouping database records and filtering grouped results. Maintain 16:9 aspect ratio, 4K quality, and perfectly readable text.

←
Post 18 of 40
→