I have SQL server 2008 R2, windows 7 OS.
Within the server, I have a table con1 which was created by following SQL statement.
CREATE TABLE [dbo].[con1](
[digit_str] [nvarchar](50) NULL
) ON [PRIMARY]
In the con1 table, I have these values:
digit_str
----------------
1
1
2
3
4
5
1.
I did executed following SQL statement against the database:
SELECT t1.digit FROM
(
select CAST(digit_str as int) as digit from con1 where RIGHT(digit_str,1) <> '.'
) as t1
where t1.digit <> 1
the server given me following error message:
Conversion failed when converting the nvarchar value ‘1.’ to data type int.
I thought my inner SQL executed first and created a temp table t1, so 1. is not included in table t1, then SQL parser will use where t1.digit <> 1 to filter temp table t1.
But above seems not right, so any one explains execution order of above SQL?
This is a known “feature” of SQL Server. Don’t ever assume that the WHERE clause executes before the SELECT clause.
See: SQL Server should not raise illogical errors
There are actually good reasons for doing that sometimes. Consider joining two tables, with A being much smaller than B.
If you inspect the query plan generated, rightly or wrongly, SQL server will stream the data from A as the leading rows to join against B. While doing that, it knows that it only needs to pull
col2andfunction on col1. It could bringcol1through just to run the function later, or for something as trivial as CAST, SQL Server might as well transform the data during the streaming process.One thing’s for sure, this strategy does make SQL Server one little bit faster in certain queries. But on a purely logical perspective, I would call it a bug.