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

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


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


A HAVING clause is just a WHERE clause after a GROUP BY. Why not put your WHERE conditions in the HAVING clause?


If it's a trick question, it's possible if the WHERE and the HAVING are not at the same level, as you mentionned, with subquery.

I guess something like that would work

HAVING value=(SELECT max(value) FROM foo WHERE crit=123)

p.s.: why were you asking?Do you have a specific problem?

p.s.s: OK silly me, I missed the "interview*" tag...