HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

Use of HAVING without GROUP BY in SQL queries

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withoutgroupsqlhavingqueriesuse

Problem

In order to use HAVING in SQL queries , must there be a GROUP BY to aggregate the column names?

Are there any special cases where it is possible to use HAVING without a GROUP BY in SQL queries?

Must they co-exist at the same time?

Solution

No.

They don't have to coexist, as proved by the fact that the following query in Oracle works:

select * from dual having 1 = 1;


Similarly, in PostgreSQL the following query works:

select 1 having 1 = 1;


So having doesn't require group by.

Having is applied after the aggregation phase and must be used if you want to filter aggregate results. So the reverse isn't true, and the following won't work:

select a, count(*) as c
from mytable
group by a
where c > 1;


You need to replace where with having in this case, as follows:

select a, count(*) as c
from mytable
group by a
having c > 1;


NB The following query form will also work:

select *
from (
  select a, count(*) as c
  from mytable
  group by a
)
where c > 1;


You can see that using having is simply a shorthand version of this last query.

In summary, having is applied after the group by phase whereas where is applied before the group by phase.

Code Snippets

select * from dual having 1 = 1;
select 1 having 1 = 1;
select a, count(*) as c
from mytable
group by a
where c > 1;
select a, count(*) as c
from mytable
group by a
having c > 1;
select *
from (
  select a, count(*) as c
  from mytable
  group by a
)
where c > 1;

Context

StackExchange Database Administrators Q#57445, answer score: 33

Revisions (0)

No revisions yet.