It's possible to have a WHERE clause after a HAVING clause?

cc. picture cc. · Nov 4, 2009 · Viewed 48.6k times · Source

Is it possible to use a WHERE clause after a HAVING clause?

The first thing that comes to my mind is sub queries, but I'm not sure.

P.S. If the answer is affirmative, could you give some examples?

Answer

Guffa picture Guffa · Nov 4, 2009

No, not in the same query.

The where clause goes before the having and the group by. If you want to filter out records before the grouping the condition goes in the where clause, and if you want to filter out grouped records the condition goes in the having clause:

select ...
from ...
where ...
group by ...
having ...

If neither of those are possible to use for some odd reason, you have to make the query a subquery so that you can put the where clause in the outer query:

select ...
from (
   select ...
   from ...
   where ...
   group by ...
   having ...
) x
where ...