Saturday, 14 September 2013

Example to HAVING Clause without GroupBy



SELECT 1 AS result
FROM dbo.Emp_Mstr
HAVING COUNT( DISTINCT eid ) = COUNT( eid );

This is more useful than it sounds. For example, consider this query to test whether the name column is unique for all values in Emp_Mstr:
 
There are only two possible results: if the HAVING clause is true then the result with be a single row containing the value 1, otherwise the result will be the empty set.
and also
SELECT 'T' AS result   
FROM Book
HAVING MIN(NumberOfPages) < MAX(NumberOfPages);
Despite the absence of the DISTINCT keyword, the query will never return more than one row. If the HAVING clause is satisfied then the result will be a single row with a single column containing the value 'T' (indicating we have books with differing numbers of pages), otherwise the result will be the empty set i.e. zero rows with a single column.
I think the reason why the query does not error in mySQL is due to propritary extensions that cause the HAVING clause to (logically) come into existence after the SELECT clause (the Standard behaviour is the other way around), coupled with the implicit GROUP BY clause mentioned in other answers.

No comments:

Post a Comment