GROUP BY groups identical values, while HAVING filters grouped results. They are commonly used with aggregate functions.
-- Syntax showing GROUP BY with HAVING
SELECT column1, COUNT(*)
FROM table
WHERE condition
GROUP BY column1
HAVING condition;
-- Sample orders table data
order_id | customer_id | amount | order_date
1 | 1 | 100 | 2021-05-10
2 | 2 | 200 | 2021-06-15
3 | 1 | 300 | 2021-07-20
4 | 3 | 400 | 2021-08-25
5 | 1 | 500 | 2021-09-30
-- Calculate total amount per customer
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id;
Each customer is grouped once and their order amounts are summed.
-- Filter grouped results using HAVING
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING SUM(amount) >= 500;