SQL: HAVING reference
22 October 2023 (Updated 22 October 2023)
On this page
In a nutshell
The HAVING
clause in MySQL is used to filter the aggregated results of a GROUP BY
operation. It is similar to the WHERE
clause, but while the WHERE
cause filters rows before they’re grouped and aggregated, the HAVING
cause filters the aggregated results.
Example
Suppose you had the following orders
table:
customer_id | order_amount |
1 | 1000 |
1 | 2000 |
2 | 4000 |
You could use the following query to find all customers and the sum of their orders:
select
customer_id,
sum(order_amount) as total
from
orders
group by
customer_id
You can then use HAVING
to filter the aggregated results:
select
customer_id,
sum(order_amount) as total
from
orders
group by
customer_id
having
total > 3000
Tagged:
MySQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment