SQL BASIC
SQL JOINS
SQL ADVANCED
SQL REFERENCE

SQL HAVING Clause

In this tutorial you'll learn how to filter the groups returned by a GROUP BY clause.

Filtering the Groups Based on Condition

The HAVING clause is typically used with the GROUP BY clause to specify a filter condition for a group or an aggregate. The HAVING clause can only be used with the SELECT statement.

To understand this easily, let's look at the following employees and departments tables.

+--------+--------------+------------+---------+
| emp_id | emp_name     | hire_date  | dept_id |
+--------+--------------+------------+---------+
|      1 | Ethan Hunt   | 2001-05-01 |       4 |
|      2 | Tony Montana | 2002-07-15 |       1 |
|      3 | Sarah Connor | 2005-10-18 |       5 |
|      4 | Rick Deckard | 2007-01-03 |       3 |
|      5 | Martin Blank | 2008-06-24 |    NULL |
+--------+--------------+------------+---------+
+---------+------------------+
| dept_id | dept_name        |
+---------+------------------+
|       1 | Administration   |
|       2 | Customer Service |
|       3 | Finance          |
|       4 | Human Resources  |
|       5 | Sales            |
+---------+------------------+
Table: employees Table: departments

Now, let's say instead of finding just name of the employees and their departments, you want to find out the names of those departments in which there are no employees.

In case of small tables you can simply apply the left join and check each departments manually, but suppose if a table contains thousands of employees then it wouldn't be so easy.

In this situation you can use the HAVING clause with the GROUP BY clause, like this:

  • SELECT t1.dept_name, count(t2.emp_id) AS total_employees
  • FROM departments AS t1 LEFT JOIN employees AS t2
  • ON t1.dept_id = t2.dept_id
  • GROUP BY t1.dept_name
  • HAVING total_employees = 0;

If you execute the above statement, you'll get the output something like this:

+------------------+-----------------+
| dept_name        | total_employees |
+------------------+-----------------+
| Customer Service |               0 |
+------------------+-----------------+

Tip: A HAVING clause is similar to a WHERE clause, but applies only to groups as a whole, whereas the WHERE clause applies to individual rows.

Note: A SELECT query can contain both a WHERE and a HAVING clause, but in that case the WHERE clause must appear before the GROUP BY clause, whereas the HAVING clause must appear after it but before the ORDER BY clause.

Your Feedback:

We would love to hear from you, please drop us a line.