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?
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?
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.
Having is used to filter groups .
where clause is used to filter rows.
having is applied after the aggregation phase so can be used to filter groups.
– Colin 't Hart
Jan 24 '14 at 08:52
In the absence of GROUP BY clause the query considers the whole relation as one group.
e.g.
select count(*)
from dual
having count(*) > 5;
HAVING is filtering the groups. If you have not GROUP BY cause, all rows presents one group. So, if predicate in HAVING evaluates as true, you get one row, otherwise no rows.
SELECT MIN(a) AS mina, MAX(a) As maxa FROM mytable HAVING MIN(a) < MAX(a);– ypercubeᵀᴹ Jan 24 '14 at 09:16select 1 having count(*) = 1;which I have yet to grasp. – Colin 't Hart Jan 24 '14 at 09:22SELECT 1 AS id, 'Colin' AS name;while others like Oracle have a specialdualtable. I don't think that either of these syntaxes is ANSI/ISO SQL (which requiresFROM). – ypercubeᵀᴹ Jan 24 '14 at 09:23frombut the reference tocount(*)in thehavingclause without any indication as to over which columns this is being aggregated. Presumably it aggregates over all columns in theselectclause. – Colin 't Hart Jan 24 '14 at 09:25select * from foo having id = 1would not work. – Jan 26 '14 at 08:53