Today’s TSQL post is an answer to a puzzle posted by Adam Machanic. I learnt something new via this puzzle today. The puzzle is as below – what would this query return?
SELECT * FROM(VALUES(1),(2)) AS x(i) WHERE EXISTS (SELECT MAX(i) FROM (VALUES(1)) AS y(i) WHERE y.i=x.i)
Upon looking at it, I thought I would get 1 row (1) – ecause the second where condition was looking for matches to 1. But I got two rows, 1 and 2. So I broke up the query as below to dig further:
SELECT * FROM
(VALUES(1),(2)) AS x(i) WHERE
EXISTS (SELECT MAX(i) FROM (VALUES(1)) AS y(i) WHERE y.i=x.i)
–this returns two rows , 1 and 2
SELECT * FROM (VALUES(1),(2)) AS x(i)
–this also returns 1 and 2
SELECT MAX(i) FROM (VALUES(1)) AS y(i)
–this returns 1
SELECT MAX(i) FROM (VALUES(2)) AS y(i)
–this returns 2
SELECT * FROM (VALUES(1),(2)) AS x(i) WHERE
EXISTS (SELECT MAX(i) FROM (VALUES(1)) AS y(i) WHERE 1=2)
–Bingo, I got my answer!! Even if exists clause is null it still returns two rows , 1 and 2.
This was a very interesting discovery and one that I will always remember when using MAX in and embedded select. Thanks, Adam.