SQL HAVING Clause

The HAVING clause in SQL is used to mention the condition to filter the result for the GROUP BY. The WHERE Clause specifies the condition for the selected column but the HAVING clause only has the condition for the GROUP BY clause.

  • Syntax of HAVING Clause –

SELECT column1,column2,column3,...,columnN FROM Table A,Table B
WHERE condition1,condition2,...
GROUP BY column1 ,column2
HAVING condition A , condition B
ORDER BY column1,column2 ;

Demo Table –

Product Table

Category City Country Customer_ID Customer_name
Office Supplies Chicago United States SM-20950 Suzanne McNair
Technology New York City United States AH-10465 Amy Hunt
Office Supplies New York City United States AH-10465 Amy Hunt
Office Supplies Dover United States EP-13915 Emily Phan
Office Supplies Dover United States EP-13915 Emily Phan
Technology Aurora United States TP-21565 Tracy Poddar
Office Supplies Aurora United States TP-21565 Tracy Poddar
Office Supplies Long Beach United States AR-10825 Anthony Rawles
Office Supplies Pasadena United States HA-14920 Helen Andreada
Furniture Pasadena United States HA-14920 Helen Andreada

Example – Consider the Product table of the Customer database where we want the result as the Count of Customers and their respective cities. The result should be grouped by the “City” and should have a Count of Customers of more than 100.

SELECT DISTINCT
COUNT
([Customer Name]) as Total_CountOfCustomer,City
FROM [dbo].[Product]
GROUP BY City
HAVING COUNT([Customer Name]) >100
ORDER BY Total_CountOfCustomer DESC ;

 

The output after implementing the above HAVING clause –

Total_CountOfCustomer City
2 Aurora
2 Dover
2 New York City
2 Pasadena
1 Chicago
1 Long Beach

 

Other SQL topics to check out:

Follow us on TwitterFacebookLinkedin, and Tableau Public to stay updated with our latest blog and what’s new in Tableau.

Automate data analysis pipeline and create report ready dashboards

If you are looking forward to getting your data pipeline built and setting up the dashboard for business intelligence, book a call now from here.