Code has been added to clipboard!

Using the SQL HAVING Clause

Reading time 1 min
Published Aug 9, 2017
Updated Oct 11, 2019

SQL HAVING Clause: Main Tips

  • The HAVING clause was added to SQL to add more functionality.
  • WHERE keyword can not be used in union with other functions. That where HAVING clause come in handy.
  • HAVING clause is often used with the COUNT function.

Syntax of SQL HAVING

Example
SELECT name_of_column(s)
FROM name_of_table
WHERE condition
GROUP BY name_of_column(s)
HAVING condition
ORDER BY name_of_column(s);

Demo Database

Let us say we have a database with information about pets.

Below is a "Pets" table:

ID City_ID Breed_ID Birthdate Country
696 90 5 2009-08-14 USA
670 81 6 2012-09-02 UK
671 34 4 2013-01-01 NO

SQL HAVING: Example

If we want to get the countries that have registered, for example, more than 2 pets, we would use HAVING clause.

The example below shows how to use it.

Example
SELECT COUNT(ID), Country
FROM Pets
GROUP BY Country
HAVING COUNT(ID) > 2;
Learn SQL
Introduction
Syntax
Data Types
Server Data Types
Commands
Commands List
Wildcards
Constraints
Aggregate Functions
Date Functions
Date Format
Injection
SQL Server Hosting
Views
Auto-incrementation
SQL Operators
AS
AND & OR
IN
BETWEEN
WHERE
GROUP BY
HAVING
ORDER BY
LIKE
NOT
NOT EQUAL
UNION
NULL
NOT NULL
DEFAULT
UNIQUE
FOREIGN KEY
PRIMARY KEY
CHECK
Indexes
ALTER TABLE
CREATE DATABASE
CREATE TABLE
DELETE
DROP
INSERT INTO SELECT
INSERT INTO
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
UPDATE
FULL OUTER JOIN
INNER JOIN
JOIN
LEFT JOIN
RIGHT JOIN
AVG()
COUNT
FIRST
LAST
MAX
MIN()
SUM()
LEN
UCASE
MID
NOW
ROUND
FORMAT
LOWER
CONVERT
ISNULL