A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

4.5 GROUP BY and HAVING clauses

 The GROUP BY clause is used to group rows that have the same values in specified columns into summary rows, like "total sales by region" or "average salary by department." The HAVING clause filters groups based on a condition.

4.5.1 GROUP BY Clause

The syntax for the GROUP BY clause is as follows:

SELECT column1, column2, aggregate_function(column3)
FROM table
GROUP BY column1, column2;

Let's consider a table named Orders:

OrderIDCustomerIDProductQuantityPrice
1101'Apples'101.00
2102'Bananas'50.75
3101'Oranges'81.25
4103'Apples'121.00
5102'Grapes'62.00

Example:

SELECT CustomerID, SUM(Quantity) AS TotalQuantity
FROM Orders
GROUP BY CustomerID;
CustomerIDTotalQuantity
10118
10211
10312

4.5.2 HAVING Clause

The HAVING clause is used to filter groups based on a condition. It is often used with the GROUP BY clause.

The syntax is as follows:

SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1
HAVING condition;

Example:

SELECT CustomerID, SUM(Quantity) AS TotalQuantity
FROM Orders
GROUP BY CustomerID
HAVING SUM(Quantity) > 15;
CustomerIDTotalQuantity
10118

In this example, only the group where the total quantity is greater than 15 is included.


Feel free to run these SQL queries in your preferred SQL Server environment to see the results. This tutorial provides a basic understanding of how to use the GROUP BY and HAVING clauses in SQL.