Can you use HAVING without GROUP BY, and what does it mean?
Yes. Without GROUP BY the entire table is treated as one implicit group, so HAVING filters that single aggregate result. It is rarely used this way in practice but is valid SQL and useful for existence checks.
How to think about it
This is a “does it work, and why?” question — and the why reveals something fundamental about HAVING. It filters groups. When there’s no GROUP BY, the whole table simply is the one group, so HAVING filters that.
What happens without GROUP BY
Omit GROUP BY and every row collapses into a single aggregate group. HAVING then acts as a gate on that one group’s aggregate value: the query returns one row if the condition holds, and zero rows if it doesn’t.
-- The table has 10 rows, so COUNT(*) > 5 is true -> one row comes back
SELECT COUNT(*) AS total_orders
FROM orders
HAVING COUNT(*) > 5;
| total_orders |
|---|
| 10 |
Change the threshold to HAVING COUNT(*) > 20 and the same query returns zero rows — the single implicit group fails the gate, so nothing passes. That all-or-nothing behaviour is the key to its one genuinely useful application.
A practical use: a one-line health check
The pattern earns its keep as a sanity gate. “Does this table have any rows?” or “Is total revenue above a threshold?” becomes a query that returns a row when healthy and nothing when not:
-- Returns one row only if there's data to process
SELECT SUM(amount) AS total_revenue
FROM orders
HAVING COUNT(*) > 0;
In pipeline validation or alerting, that’s a tidy way to short-circuit downstream steps when a table is unexpectedly empty — the empty result set is the signal.
When a subquery is clearer
For most in-application checks, computing the value and testing it in code reads more plainly than a bare HAVING:
SELECT COUNT(*) FROM orders; -- then check the value in your application
HAVING without GROUP BY is valid and occasionally elegant for in-query conditionals, but a colleague usually parses a subquery-plus-WHERE faster.