Join waitlist
SQLCommunity question

WHERE vs HAVING - can you use HAVING without GROUP BY?

Asked by Ritika Malhotra 2 months ago 3 answers 12 votes

I know WHERE filters rows before grouping and HAVING filters groups after. But a quiz asked whether HAVING works without GROUP BY and I said no. Answer was yes? How does that even work

3 answers

Pooja Patel2 months agoMost voted10

Yes it works. Without GROUP BY the whole result is treated as one single group.

SELECT SUM(amount) FROM orders HAVING SUM(amount) > 1000;

returns one row if the total is above 1000, otherwise nothing.

Also helps to remember the logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. That's also why you can't use a SELECT alias inside WHERE.

Farhan Ali2 months ago3

and if a condition doesn't need an aggregate, put it in WHERE not HAVING. less rows to group

Ritika Malhotra2 months ago1

ah ok makes sense, whole table = one group

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.