EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials SQL Tutorial SQL HAVING Clause
Secondary Sidebar
SQL Tutorial
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL SELECT DISTINCT Multiple Columns
    • SQL Null Values
    • SQL LIKE
    • SQL LIKE Query
    • SQL LIKE Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • SQL HAVING Clause
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Quick References
    • SQL Like Wildcard
    • SQL Like with Multiple Values
    • SQL Examples
    • SQL Server Versions
    • SQL DROP DB
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • SQL Foreign Key
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • SQL UNIQUE Constraint
    • SQL Primary Key
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL Server Functions
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL REGEX
    • SQL Window Functions
    • SQL Syntax
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL Min and Max
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite? functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Ranking Function
    • SQL Server Permission
  • T-SQL
    • T-SQL pivot
    • T-SQL Formatter
    • T-SQL TRY CATCH
    • T-SQL CTE
    • T-SQL CASE
    • T-SQL DATEPART
    • T-SQL Date Format
    • T-SQL ROUND
    • T-SQL Loop
    • T-SQL IIF
    • T-SQL Union
    • T-SQL CREATE TABLE
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ISNULL
    • T-SQL ADD Column
    • T-SQL DATEDIFF
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • MDF File in SQL Server
    • SQL Aliases
    • SQL Hosting
    • SQL Auto Increment
    • SQL Injection
    • SQL Wildcards
    • SQL Check
    • SQL Indexes
    • Select Distinct
    • SQL BETWEEN
    • SQLPlus spool
    • SQL Create Table
    • SQL Schema
    • Comparison Operators in SQL
    • SQL_plus
    • SQL Formatter
    • SQL LEFT INNER JOIN
    • SQL Plus Command
    • SQLPlus not found
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • SQL DROP Table
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • SqlAlchemy
    • What is SQLAlchemy
    • SqlAlchemy ORM
    • SQLAlchemy count
    • SQLAlchemy update object
    • SQLAlchemy pip
    • SQLAlchemy Connection
    • SQLAlchemy Metadata
    • SQLAlchemy Raw SQL
    • SQLAlchemy Filter in List
    • SQLAlchemy Alias
    • SQLAlchemy unique
    • SQLAlchemy JSONB
    • SQLAlchemy Async
    • SQLAlchemy Types
    • SQLAlchemy Many to Many
    • SQLAlchemy Example
    • SQLAlchemy Model
    • SQLAlchemy Data Types
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQLAlchemy Delete
    • SQLAlchemy Migrations
  • NoSQL
    • NoSQL Databases List
    • NoSQL Data Modeling
    • Types of NoSQL Databases
    • NoSQL Injection
    • NoSQL vs SQL Databases
    • NoSQL Use Cases
    • NoSQL Key Value
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions
    • SQL Current Month

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

SQL HAVING Clause

By Priya PedamkarPriya Pedamkar

SQL HAVING Clause

Introduction to SQL HAVING Clause

‘Having’ clause in SQL is used for aggregation operations along with ‘Where’, ‘group by’ & ‘order by’ condition statements. It is applied on a table/ database where there is a need for filtering aggregate results and allows ‘group by’ and ‘order by’ conditions. When the ‘having’ clause is used in a query, it is expected that the resulting output data set can have more than one record from the table/ database.

Why HAVING and not WHERE?

We see that HAVING and WHERE clauses perform a very similar task to filter out the results. Then what was the need for the HAVING clause? Why couldn’t the WHERE clause be used with aggregate functions?

To answer this, we would need to understand how the SQL engine treats the two clauses. The FROM clause in every SQL command tells the engine from where to read the rows. The data is stored on the disk and is fetched into the memory for processing. As the rows are read one by one from the disk to the memory, they are checked for the WHERE clause. The rows that fail the WHERE clause aren’t loaded into the memory. Thus, the WHERE clause is evaluated for each row as the SQL engine processes them.

On the contrary, the HAVING clause comes into the picture only after the rows have been loaded into the memory. Once loaded into the memory, the aggregate functions perform their task on the rows HAVING the desired condition.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Now, if we were to put a WHERE clause with the aggregate function such as avg(), this would confuse the SQL engine on whether to include the row for calculating the average or not. Essentially, we would be commanding the engine to not read the row since it did not pass the avg() criteria in the WHERE clause. But hey, to determine whether it passed or failed the avg() calculation criteria, the row needs to be read into the memory. A state of deadlock.

Syntax:

SELECT <column(s)>
FROM <table>
WHERE <condition>          -- optional
GROUP BY <column(s)>       -- groups the rows to apply aggregate function
HAVING <condition>         -- aggregate function in the condition
ORDER BY <column(s)>;      -- define the sorting order, optional

Note: GROUP BY clause is required with the HAVING clause. This is because the Having clause needs a group of data to apply an aggregate function and filter out the results.

How HAVING Clause Works?

The GROUP BY clause always accompanies the HAVING clause. The GROUP BY clause groups together the data that match a certain criterion. It has three phases – split, apply, and combine. The split-phase divides the rows into groups. The apply phase applies some aggregate functions on the groups of data. The combined phase produces a single result by combining the groups with the aggregate function result.

Now that the groups are formed, the HAVING clause comes into the picture. The HAVING clause then filters out the groups which do not satisfy the given condition.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)

How HAVING clause works

Code:

SELECT Col_A, avg(Col_B) as Col_B
FROM MyTable
GROUP BY Col_A
HAVING avg(Col_B)>30

Thus, in the example above, we see that the table is first to split into three groups based on the column Col­_A. The aggregate function to calculate the average of Col­_B values is then applied to the groups. This results in a single row for each group. The rows are then combined and filtered based on the condition in the HAVING clause.

Example

Now let us look at a real-world example.

Consider we have the following table of customers and the orders that they have placed with us.

CustomerID CustomerName City Country
1 Anja Damian Berlin Germany
2 Denny Cockett México D.F. Mexico
3 Eleanor Calnan México D.F. Mexico
4 Albertha Albury London UK
5 Latisha Nembhard Luleå Sweden
6 Madalene Bing Mannheim Germany
7 Rebecka Beegle Strasbourg France
8 Rosy Tippie Madrid Spain
9 Audie Khan Marseille France
10 Hildegard Burrowes Tsawassen Canada
11 Cordell Dutremble London UK
12 Nora Reyna Buenos Aires Argentina
13 Ursula Laforest México D.F. Mexico
14 Claudie Neel Bern Switzerland
15 Portia Yee São Paulo Brazil
16 Angila Segarra London UK
17 Lise Wexler Aachen Germany
18 Ned Mendivil Nantes France
19 Sara Vidaurri London UK
20 Tayna Navin Graz Austria
21 Pura Ray São Paulo Brazil
22 Erika Byard Madrid Spain
23 Jimmie Luke Lille France
24 Shayla Byington Bräcke Sweden
25 Christiana Boden München Germany
26 Irina Nitta Nantes France
27 Bryanna Alls Torino Italy
28 Norah Picken Lisboa Portugal
29 Moriah Stwart Barcelona Spain
30 Idella Harriott Sevilla Spain
OrderID CustomerID OrderDate
10254 14 11-07-1996
10258 20 17-07-1996
10259 13 18-07-1996
10263 20 23-07-1996
10264 24 24-07-1996
10265 7 25-07-1996
10267 25 29-07-1996
10278 5 12-08-1996
10280 5 14-08-1996
10289 11 26-08-1996
10290 15 27-08-1996
10297 7 04-09-1996
10303 30 11-09-1996
10308 2 18-09-1996
10311 18 20-09-1996
10326 8 10-10-1996
10327 24 11-10-1996
10328 28 14-10-1996
10331 9 16-10-1996
10337 25 24-10-1996
10340 9 29-10-1996
10342 25 30-10-1996
10347 21 06-11-1996
10351 20 11-11-1996
10352 28 12-11-1996
10355 4 15-11-1996
10360 7 22-11-1996
10362 9 25-11-1996
10363 17 26-11-1996
10364 19 26-11-1996
10365 3 27-11-1996
10366 29 28-11-1996
10368 20 29-11-1996
10370 14 03-12-1996
10378 24 10-12-1996
10382 20 13-12-1996
10383 4 16-12-1996
10384 5 16-12-1996
10386 21 18-12-1996
10389 10 20-12-1996
10390 20 23-12-1996
10391 17 23-12-1996
10396 25 27-12-1996
10400 19 01-01-1997
10402 20 02-01-1997
10403 20 03-01-1997
10408 23 08-01-1997
10410 10 10-01-1997
10411 10 10-01-1997
10414 21 14-01-1997
10422 27 22-01-1997
10426 29 27-01-1997
10430 20 30-01-1997
10431 10 30-01-1997
10434 24 03-02-1997
10435 16 04-02-1997
10436 7 05-02-1997
10442 20 11-02-1997

Now, we want to know customers of which countries have placed a combined total of 5 or more orders with us. It could be a single customer placing more than 5 orders or 5 customers placing 1 order each.

To accomplish this, we would need to:

Step 1: Join the two tables.

Step 2: Group the customers based on their countries.

Step 3: Count the number of orders for each group.

Step 4: Filter the results for 5 or more orders.

Let’s formulate the command:

Code:

SELECT C.Country, COUNT(O.OrderId) as NumberOfOrders         -- Step 1,3
FROM Customers C                                                -- Step 1
INNER JOIN Orders O on C.CustomerID = O.CustomerID              -- Step 1
GROUP BY C.Country                                              -- Step 2
HAVING COUNT(O.OrderId) >= 5                                    -- Step 4
ORDER BY COUNT(O.OrderId) DESC

Here are the results:

Country NumberOfOrders
Austria 10
France 9
Sweden 7
Germany 6
UK 6

Conclusion – SQL HAVING Clause

Thus, we have seen what the purpose of the HAVING clause is and how does it work. It is important to understand the basic working, or else you may end up getting confused about why the HAVING clause is not producing the desired results. Keep playing with various tables and joins and combinations along with the HAVING clause.

Recommended Articles

This is a guide to SQL HAVING Clause. Here we discuss working of the HAVING clause in SQL and the example with the following table of customers. You can also go through our other suggested articles –

  1. SQL Insert Query
  2. Foreign Key in SQL
  3. Distinct Keyword in SQL
  4. SQL Views
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

JDBC Training (6 Courses, 7+ Projects)4.9
PHP Training (5 Courses, 3 Project)4.8
Windows 10 Training (4 Courses, 4+ Projects)4.7
PL SQL Training (4 Courses, 2+ Projects)4.7
Oracle Training (14 Courses, 8+ Projects)4.7
2 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more