89

This sql code throws an

aggregate functions are not allowed in WHERE

SELECT o.ID ,  count(p.CAT)
FROM Orders o
INNER JOIN Products p ON o.P_ID = p.P_ID 
WHERE count(p.CAT) > 3
GROUP BY o.ID;

How can I avoid this error?

4 Answers 4

152

Replace WHERE clause with HAVING, like this:

SELECT o.ID ,  count(p.CAT)
FROM Orders o
INNER JOIN Products p ON o.P_ID = p.P_ID 
GROUP BY o.ID
HAVING count(p.CAT) > 3;

HAVING is similar to WHERE, that is both are used to filter the resulting records but HAVING is used to filter on aggregated data (when GROUP BY is used).

15

Use HAVING clause instead of WHERE

Try this:

SELECT o.ID, COUNT(p.CAT) cnt
FROM Orders o
INNER JOIN Products p ON o.P_ID = p.P_ID 
GROUP BY o.ID HAVING cnt > 3
1

try this. WHERE (select (count(p.CAT) > 3) from TableName)

2
  • Could you clarify how this resolves the question being asked?
    – Skully
    Dec 15, 2022 at 12:17
  • Awesome, this did work wonders for me. I was in a situation where I could only change what was inside an already existing WHERE (thus not able to use having). Jan 29 at 7:18
0

Will self join will go for a toss with join where we have a condition to list prices that are greater than the median of the prices listed in the order table?

Eg. order_item, Order_Price

Since aggregate functions cannot be used in a WHERE clause >

select a.order_item_product_price, count(distinct 
a.order_item_product_price) from 
default.order_items a , default.order_items b
where a.order_item_product_price = b.order_item_product_price
group by a.order_item_product_price
having a.order_item_product_price > appx_median(b.order_item_product_price)
order by a.order_item_product_price limit 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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