I came across this puzzle in the comments here
CREATE TABLE r (b INT);
SELECT 1 FROM r HAVING 1=1;
SQL Server and PostgreSQL return 1 row.
MySQL and Oracle return zero rows.
Which is correct? Or are both equally valid?
aggregatesql-standard
I came across this puzzle in the comments here
CREATE TABLE r (b INT);
SELECT 1 FROM r HAVING 1=1;
SQL Server and PostgreSQL return 1 row.
MySQL and Oracle return zero rows.
Which is correct? Or are both equally valid?
Best Answer
Per the standard:
means
Citation ISO/IEC 9075-2:2011 7.10 Syntax Rule 1 (Part of the definition of the HAVING clause):
Ok so that much is pretty clear.
Assertion:
1=1
is true search condition. I will provide no citation for this.Now
is equivlent to
Citation ISO/IEC 9075-2:2011 7.10 General Rule 1:
Logic: Since the search condition is always true, the result is
R
, which is the result of the group by expression.The following is an excerpt from the General Rules of 7.9 (the definition of the GROUP BY CLAUSE)
Thus we can conclude that
results in a grouped table, consisting of one group, with zero rows (since R is empty).
An excerpt from the General Rules of 7.12, which defines a Query Specification (a.k.a a SELECT statement):
Therefore since the table has one group, it must have one result row.
Thus
should return a 1 row result set.
Q.E.D.