TExcelTAD
Home › MySQL › MySQL HAVING

MySQL HAVING

WHERE filters rows before they are grouped. HAVING filters groups after the aggregates have been computed, so it can test conditions such as COUNT(*) > 2 or SUM(...) >= 100.

sql
SELECT group_column, AGGREGATE(expr)
FROM table_name
WHERE row_condition
GROUP BY group_column
HAVING group_condition
ORDER BY ...;

"Customers who placed at least two orders":

mysql · try it yourself
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2
ORDER BY orders DESC, customer_id;
+-------------+--------+
| customer_id | orders |
+-------------+--------+
|           1 |      3 |
|           2 |      3 |
|           4 |      2 |
|           5 |      2 |
|           6 |      2 |
|           8 |      2 |
|          12 |      2 |
+-------------+--------+

Writing WHERE COUNT(*) >= 2 would be an error: when WHERE runs there are no groups yet.

WHERE and HAVING together

They often appear in the same query, each doing its own job. "Among orders that weren't cancelled, which products sold more than 5 units?":

mysql · try it yourself
SELECT p.name, SUM(d.quantity) AS units
FROM order_details AS d
JOIN orders   AS o ON o.order_id = d.order_id
JOIN products AS p ON p.product_id = d.product_id
WHERE o.status <> 'cancelled'
GROUP BY p.product_id, p.name
HAVING SUM(d.quantity) > 5
ORDER BY units DESC, p.name;
+--------------------+-------+
| name               | units |
+--------------------+-------+
| Butter Croissant   |    18 |
| Sea Salt Crisps    |    12 |
| Whole Milk 1L      |    12 |
| Avocado (each)     |    10 |
| Dark Chocolate Bar |    10 |
| Orange Juice 1L    |     9 |
| Earl Grey Tea      |     8 |
| Gala Apples 1kg    |     7 |
| Greek Yogurt 500g  |     6 |
+--------------------+-------+

The order of work is: FROM/JOIN builds the rows, WHERE drops the cancelled orders' lines, GROUP BY forms one group per product, HAVING keeps the groups over 5 units, and ORDER BY sorts what's left.

Tip: If a condition doesn't involve an aggregate, put it in WHERE, not HAVING. Both may give the same result, but WHERE throws rows away early, so there is less to group.

Using aliases in HAVING

MySQL allows a select-list alias in HAVING, which saves repeating a long expression:

mysql · try it yourself
SELECT o.order_id,
       ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2) AS order_total
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
GROUP BY o.order_id
HAVING order_total > 30
ORDER BY order_total DESC;
+----------+-------------+
| order_id | order_total |
+----------+-------------+
|        4 |       59.00 |
|       15 |       36.50 |
|       14 |       35.21 |
|       10 |       34.38 |
|        1 |       33.80 |
|       19 |       32.45 |
|        5 |       32.30 |
+----------+-------------+

Conditions on several aggregates

HAVING can combine conditions with AND/OR like WHERE. Categories with at least 3 products and an average price under 5:

mysql · try it yourself
SELECT category_id, COUNT(*) AS products, ROUND(AVG(unit_price), 2) AS avg_price
FROM products
GROUP BY category_id
HAVING COUNT(*) >= 3 AND AVG(unit_price) < 5
ORDER BY category_id;
+-------------+----------+-----------+
| category_id | products | avg_price |
+-------------+----------+-----------+
|           3 |        4 |      4.05 |
|           4 |        3 |      2.33 |
|           5 |        3 |      3.32 |
+-------------+----------+-----------+

Test yourself

Which clause filters groups after aggregation?

  1. WHERE
  2. HAVING
  3. ORDER BY
  4. LIMIT

In which order are these clauses evaluated?

  1. SELECT, WHERE, GROUP BY, HAVING
  2. WHERE, GROUP BY, HAVING, ORDER BY
  3. HAVING, WHERE, GROUP BY, ORDER BY
  4. GROUP BY, WHERE, HAVING, ORDER BY

Where should status <> 'cancelled' go in a grouped query?

  1. HAVING, because it is grouped
  2. WHERE, because it is a row condition
  3. ORDER BY
  4. Either is an error