1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

46 Lessons
45

SQL HAVING with Examples

Updated on 25/06/202444 Views

Introduction

Structured Query Language (SQL) is one of the pillars of the vast realm of database management systems. One of the most potent arsenals in SQL’s repertoire for extracting actionable insights from intricate datasets is the HAVING clause. In conjunction with the GROUP BY clause, HAVING is a super-effective tool for filtering and analyzing data based on predefined conditions. This comprehensive guide will go deep into the nuances of SQL HAVING clauses with real-life HAVING EXAMPLES in SQL showcasing the use of HAVING clauses in SQL. 

SELECT

FROM

WHERE

GROUP BY

HAVING

ORDER BY

What is SQL HAVING?

Fundamentally, SQL HAVING functions as a filter for grouped datasets. Though its syntax is like the WHERE clause, HAVING filters grouped rows based on predefined conditions. This is unlike the WHERE clause, which filters individual rows before grouping. Since the HAVING clause is specifically used in conjunction with the GROUP BY clause, it imposes conditions on groups rather than specific rows.

The following is the common syntax for the HAVING clause:

SELECT column1, aggregate_function(column2)

FROM table_name

GROUP BY column1

HAVING condition;

What are the Differences between HAVING and WHERE Clauses?

Notable differences between HAVING and WHERE in SQL are:

  1. Timing of Application: The WHERE clause is used to filter rows before they are grouped, while the HAVING clause is used to filter the grouped data after it has been grouped.
  2. Application Scope: The WHERE clause is used to apply conditions to individual rows, while the HAVING clause is used to apply conditions to groups of rows.
  3. Usage with Aggregate Function: When it comes to using aggregate functions, there is a key difference between the WHERE clause and the HAVING clause. While the WHERE clause cannot be directly used with aggregate functions, the HAVING clause is specifically designed to handle conditions involving aggregate functions.
  4. Applications: The WHERE clause is used to filter individual rows based on column values, while the HAVING clause is used to filter grouped data based on aggregate results.

Picture this: for all the queries in this tutorial, we will consider a sample table named "sales_data" with columns: product, region, quantity_sold, and price.

Using the WHERE Clause:

To select products sold in the 'East' region with a quantity sold greater than 100.

SELECT *

FROM sales_data

WHERE region = 'East' AND quantity_sold > 100;

Using the HAVING Clause:

Extract regions with total sales exceeding $10,000.

SELECT region, SUM(price * quantity_sold) AS total_sales

FROM sales_data

GROUP BY region

HAVING SUM(price * quantity_sold) > 10000;

In this example, the WHERE clause filters rows before grouping. The HAVING clause filters grouped data by the product column based on aggregate results after grouping.

We saw in the above example that the WHERE and HAVING clauses work in different ways to perform the same task. This lends a wider spectrum to SQL queries when it comes to data filtering and analysis.

Let’s Look at GROUP BY and HAVING SQL

GROUP BY clause: To divide the result set into separate groups depending on the provided column criteria, the GROUP BY clause in SQL consolidates rows with identical values into summary rows. It allows for the independent calculation of values for each group and is usually used in conjunction with aggregate operations such as SUM(), AVG(), COUNT(), etc. Data aggregation jobs rely on this clause since it enables calculation and analysis across defined categories in a dataset.

Correlation with the HAVING clause: The combination of the GROUP BY HAVING clause in SQL is frequently employed in SQL queries. The GROUP BY clause partitions the result set into several groups, while the HAVING clause selectively filters these groups according to specified constraints. The HAVING clause is executed after the GROUP BY clause, thereby operating on the groups that are produced by the GROUP BY clause.

Why Do We Use HAVING Instead of the WHERE Clause?

Instead of the WHERE clause, the HAVING clause is utilized to filter aggregated data according to aggregate conditions. In contrast to the WHERE clause, which filters individual rows before grouping, the HAVING clause applies conditions to aggregate results after grouping, thereby enabling the application of conditions to grouped data rather than individual rows. So, now you understand why HAVING plays such an important role in extracting and analyzing truncated datasets.

Distinction between GROUP BY and HAVING Clauses

  1. Application Scope: The result set is divided into groups by the GROUP BY clause, and the HAVING clause filters these groups based on aggregate conditions.
  2. Application Timing: The application of GROUP BY occurs before the data is aggregated, while HAVING is applied after the data has been aggregated.
  3. Here's how it Works: GROUP BY is used to group data together and create categories, while HAVING is used to filter those categories based on specific conditions.
  4. Pre-conditions: When working with aggregate functions, GROUP BY is commonly used to group the data, while HAVING is used to set conditions for those aggregate functions.

Example:

Imagine the same scenario as above, where a sample table named "sales_data" with columns: product, region, quantity_sold, and price. 

SELECT region, SUM(price * quantity_sold) AS total_sales

FROM sales_data

GROUP BY region;

Here, we're using a GROUP BY Group sales data by region to calculate total sales for each region.

Use of HAVING Clause in SQL

Executing SQL statements with the HAVING clause in SQL enables you to filter aggregated data according to specific conditions. Although the HAVING clause and the WHERE clause are similar in that they both filter individual rows, the former applies to aggregated data after the GROUP BY clause's grouping of the data. Let's examine some additional use cases to gain a deeper understanding of its versatility:

1. Group Filtering by Count:

Take advantage of the HAVING clause to select products with more than 50 sales.

SELECT product, COUNT(*) AS total_sales

FROM sales_data

GROUP BY product

HAVING COUNT(*) > 50;

2. Group Filtering by Average: 

Filtering groups according to their average price per unit ($20 in this case) can be accomplished by using the HAVING clause.

SELECT product, AVG(price) AS avg_price

FROM sales_data

GROUP BY product

HAVING AVG(price) > 20;

3. Group Filtering by Sum:

We can find regions with total sales exceeding $10,000.

SELECT region, SUM(price * quantity_sold) AS total_sales

FROM sales_data

GROUP BY region

HAVING SUM(price * quantity_sold) > 10000;


4. Group Filtering by Maximum Value:

Here, we can identify products with a maximum price exceeding $100.

SELECT product, MAX(price) AS max_price

FROM sales_data

GROUP BY product

HAVING MAX(price) > 100;


5. Group Filtering by Minimum Value:

Make use of the HAVING clause to find regions with a minimum quantity sold exceeding 50 units.

SELECT region, MIN(quantity_sold) AS min_quantity_sold

FROM sales_data

GROUP BY region

HAVING MIN(quantity_sold) > 50;


6. Group Filtering by Multiple Conditions:

The HAVING clause can be used to combine numerous conditions to filter groups efficiently, such as retrieving regions with total sales exceeding $10,000 and an average price per unit greater than $50.

SELECT region, SUM(price * quantity_sold) AS total_sales, AVG(price) AS avg_price

FROM sales_data

GROUP BY region

HAVING SUM(price * quantity_sold) > 10000 AND AVG(price) > 50;


The HAVING clause in SQL is pretty nifty. It lets you filter grouped data in a detailed way so that you can analyze and get the exact information based on certain conditions. The HAVING clause in SQL is a true gem; it's like your secret weapon for spotting those data outliers or categorizing information based on particular rules—really, an invaluable tool when you're deep-diving into any kind of data analysis.

SQL HAVING Examples

There are many HAVING examples in SQL in real life. Let’s look at some of the common use cases of this efficient SQL tool.

Regional Sales Analysis: 

SELECT region, SUM(price * quantity_sold) AS total_sales

FROM sales_data

GROUP BY region;


This can be used to calculate total sales for each region.

Evaluating Employee Performance:

SELECT department, AVG(quantity_sold) AS avg_quantity_sold

FROM sales_data

GROUP BY department;


We can determine the average quantity sold by a particular department.

Inventory Management:

SELECT product

FROM sales_data

GROUP BY product

HAVING SUM(quantity_sold) < 50;


This example picks up on products where the sales quantity is less than 50.

Customer Segmentation:

SELECT customer_id, SUM(price * quantity_sold) AS total_purchases

FROM sales_data

GROUP BY customer_id;


You can see how marketing departments can segment customers based on purchases.

Financial Evaluation:

SELECT SUM(price * quantity_sold) AS total_revenue

FROM sales_data;


You can use this to find out the total revenue.

Conclusion

So, to put it simply, when you're dealing with SQL HAVING, the GROUP BY and HAVING clauses are key players in smart data analysis. Looking at a bunch of different SQL GROUP BY HAVING examples, it's clear to see the good stuff they bring to the table—think better ways to sell things and smarter use of resources. We harness the power of HAVING count SQL and GROUP BY HAVING count. They unlock a realm full of potential. In this realm, data-driven decisions become a key to charting our path. 

In this ceaselessly shifting landscape, let's embrace these technological marvels as the ignition for our creative engines and the accelerators propelling us forward with the help of the HAVING clause EXAMPLES we discussed in the article. 

FAQs

Q: Is HAVING a command in SQL?

A: HAVING is not a command on its own. It’s a clause that filters grouped datasets in conjunction with the SELECT statement.

Q: Where can we use HAVING?

A: In order to utilize the HAVING clause, SELECT statements must contain a GROUP BY clause. Grouped data is filtered according to predefined conditions. 

Q: What is faster, WHERE or HAVING?

A: Typically, the WHERE clause is more efficient than the HAVING clause because it applies to individual rows before they are grouped. Nevertheless, the disparity in performance may fluctuate based on the particular query and the optimization of the database. 

Q: Can we use HAVING with GROUP BY in SQL?

A: Using the GROUP BY clause is necessary when utilizing the HAVING clause. It is essential to consider the aggregated conditions when filtering groups of rows. Without the presence of GROUP BY, there will be no groups available for filtering.

Pavan Vadapalli

Pavan Vadapalli

Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and l… Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...