loading

MySQL HAVING

The MySQL HAVING Clause

Because aggregate functions cannot use the WHERE keyword, the HAVING clause was added to SQL.

HAVING Syntax

				
					SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
				
			

Demo Database

Below is a selection from the “Customers” table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1

Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4

Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

MySQL HAVING Examples

The number of customers in each nation is listed in the SQL statement that follows. Add only those nations where there are five or more customers:

Example

				
					SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
				
			

The number of clients in each nation is listed in the SQL statement that follows, sorted from high to low (only include countries with more than 5 customers):

Example

				
					SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
				
			

Demo Database

Below is a selection from the “Orders” table in the Northwind sample database:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

And a selection from the “Employees” table:

EmployeeIDLastNameFirstNameBirthDatePhotoNotes
1DavolioNancy1968-12-08EmpID1.picEducation includes a BA….
2FullerAndrew1952-02-19EmpID2.picAndrew received his BTS….
3LeverlingJanet1963-08-30EmpID3.picJanet has a BS degree….

More HAVING Examples

The employees who have registered more than ten orders are listed in the SQL statement that follows:

Example

				
					SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
				
			

The SQL query that follows indicates whether workers “Davolio” or “Fuller” have more than 25 orders registered:

Example

				
					SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
				
			
Share this Doc

MySQL HAVING

Or copy link

Explore Topic