I would like to know if it is possible to evaluate expressions that are part of a list of SELECT for rows that do not match the WHERE ?
From the execution order described here , it seems that SELECT is evaluated long after WHERE , however, I ran into a very strange problem with a real query similar to the query below .
To bring you into context, in the example SomeOtherTable has SomeOtherTable column, which always contains numeric values ββfor code 105, but may contain non-numeric values ββfor other codes.
The query operator works:
SELECT an_id, an_integer FROM SomeTable UNION ALL SELECT an_id, CAST(a_varchar AS int) FROM SomeOtherTable WHERE code = 105
The following request complains that it cannot pass a_varchar to int :
SELECT 1 FROM ( SELECT an_id, an_integer FROM SomeTable UNION ALL SELECT an_id, CAST(a_varchar AS int) FROM SomeOtherTable WHERE code = 105 ) i INNER JOIN AnotherOne a ON a.an_id = i.an_id
And finally, the following query works:
SELECT 1 FROM ( SELECT an_id, an_integer FROM SomeTable UNION ALL SELECT an_id, CASE code WHEN 105 THEN CAST(a_varchar AS int) ELSE NULL END FROM SomeOtherTable WHERE code = 105 ) i INNER JOIN AnotherOne a ON a.an_id = i.an_id
Therefore, the only explanation I could find was that with JOIN request will be optimized differently so that CAST(a_varchar AS int) will be executed even if code <> 105 .
Queries are launched in SQL SERVER 2008.