Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid error "aggregate functions are not allowed in WHERE"

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?

like image 296
D-Lef Avatar asked Jan 08 '14 09:01

D-Lef


People also ask

Why are aggregate functions not allowed in WHERE clause?

Aggregate functions work on sets of data. A WHERE clause doesn't have access to entire set, but only to the row that it is currently working on.

Can aggregate functions be used in WHERE?

An aggregate function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name, each column name must be a correlated reference to the same group.

Which clause is that aggregate functions Cannot be used in?

Aggregate functions can be used in both the SELECT and HAVING clauses (the HAVING clause is covered later in this chapter). Aggregate functions cannot be used in a WHERE clause.

Can we use aggregate functions to filter values in WHERE class?

You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for. You can use a sub-query which contains an aggregate in the WHERE clause.


1 Answers

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).

like image 118
Aziz Shaikh Avatar answered Sep 19 '22 22:09

Aziz Shaikh