MySQL HAVING Clause
Introduction to MySQL HAVING clause
The MySQL HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates.
The HAVING clause is used in combination with the GROUP BY clause to filter groups based on a specified condition. It always returns the rows where condition is TRUE.
HAVING Clause Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) HAVING condition ORDER BY column_name(s);
To understand MySQL HAVING clause , consider an “customers” table, which is having the following records:
SELECT * FROM customers;
CustomerID | CustomerName | Age | City | Country |
---|---|---|---|---|
1 | Christina | 40 | London | United Kingdom |
2 | Maria Anders | 56 | Berlin | Germany |
3 | Matthew | 34 | Luleå | Sweden |
4 | Alen | 51 | Berlin | Germany |
5 | Jacob | 28 | México D.F | Mexico |
6 | Aastha | 26 | Chandigarh | India |
7 | Joshua | 21 | México D.F | Mexico |
Now suppose based on the above table you want to count the number of customers in each country. Only include countries with more than 1 customers, then you can do it as follows:
SELECT COUNT(CustomerID) AS "Number of customers", Country FROM customers GROUP BY Country HAVING COUNT(CustomerID) > 1;
Number of customers | Country |
---|---|
2 | Germany |
2 | Mexico |
Below is a selection from the “orders” table, which is having the following records:
SELECT * FROM orders;
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 2 | 2017-02-02 |
2 | 2 | 2017-03-23 |
3 | 4 | 2017-06-14 |
4 | 5 | 2017-06-17 |
5 | 6 | 2017-07-28 |
6 | 6 | 2017-07-31 |
7 | 7 | 2017-09-10 |
8 | 6 | 2017-09-12 |
The following MySQL statement lists the customers that have more than 2 orders:
SELECT CustomerName, COUNT(orders.OrderID) AS TotalOrder FROM customers INNER JOIN Orders ON customers.CustomerID = orders.CustomerID GROUP BY customers.CustomerID HAVING TotalOrder > 2;
CustomerName | TotalOrder |
---|---|
Aastha | 3 |