2

I have a table with order id, product id and the quantity of each product of that order (like in the table below). And I have to select the order_id and it's total quantity where the quantity is more than 5.

+----------+------------+----------+
| order_id | product_id | quantity |
+----------+------------+----------+
|        1 |          1 |        6 |
|        1 |          2 |        1 |
|        2 |          3 |        3 |
|        2 |          2 |        2 |
|        3 |          1 |        3 |
|        3 |          3 |        5 |
+----------+------------+----------+

What I've tried is

SELECT order_id, SUM(quantity) AS qty
FROM order_product
WHERE qty > 5 /* <-- Cannot use qty here */
GROUP BY order_id;

ERROR 1054 (42S22): Unknown column 'qty' in 'where clause'

AFAIK the where clause executed before summing the quantity columns so I cannot use qty there but is there any way to run the condition after the aggregation or is there any other way to solve it?

1 Answer 1

8

To filter after aggregation, you can use a HAVING clause.

SELECT order_id,
       sum(quantity) AS qty
       FROM order_product
       GROUP BY order_id
       HAVING sum(quantity) > 5;
3
  • ... also the output alias instead of the expression can be used: HAVING qty > 5. (may be useful for OP)
    – Akina
    Commented Jan 2, 2022 at 20:41
  • 1
    How can this completely basic question not be a duplicate. And how did this end up being a HNQ?
    – Barmar
    Commented Jan 3, 2022 at 16:04
  • @Barmar - I find it easier/faster to answer a question than to look for a dup and study the potential dup to see if it really matches. (I find a lot of "closed as dup" questions there were not a good match.) Otherwise, I agree; it must be a dup.
    – Rick James
    Commented Jan 3, 2022 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.