MySQL Tutorial – Using HAVING clause

Using HAVING clause

HAVING clause is somewhat similar to WHERE clause and it is used together with the GROUP BY clause. It was added to SQL to combine with the aggregate functions because the WHERE clause doesn’t allow aggregates.

The syntax of HAVING clause:

SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Let’s see some example:

database table: (employee_record)

[TABLE=3]

We want to list the position of the employee that is having a salary greater then 20000. Issue the following command:

SELECT position, MAX(salary)
FROM employee_record
GROUP BY position
HAVING MAX(salary) > 20000;

Result:

+------------+-------------+
| position   | MAX(salary) |
+------------+-------------+
| Encoder    |       55000 |
| Programmer |       25000 |
+------------+-------------+
2 rows in set (0.00 sec)
, , ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.