I was writing another query, and became enamored with the fact that HAVING will accept IS NULL or IS NOT NULL as a predicate.
What I ended up writing as an example was this query:
SELECT v.PostId, SUM(v.UserId) AS whatever
FROM dbo.Votes AS v
WHERE v.UserId IS NULL
GROUP BY v.PostId
HAVING SUM(v.UserId) IS NOT NULL;
Why this query?
I figured the optimizer would take one look at it and bail out with a Constant Scan.
After all, the WHERE clause filters to only NULL UserIds, and this column is NULLable in the Votes table.
The HAVING could only ever produce a NULL. And according to the laws of Logical Query Processing, WHERE is processed earlier than HAVING is.
But that’s not what happens.
Query At Work
Just may kick my butt in the comments about why this doesn’t bail out. My soul and butt are prepared.
Thanks for reading!