Possible Duplicate:
Column does not exist in the IN clause, but SQL runs
I stumbled upon this today while at work today and I was wondering, why is it that the following code does not generate and error?
CREATE TABLE #TableA (ColumnA VARCHAR(25))
CREATE TABLE #TableB (ColumnB VARCHAR(25))
INSERT INTO #TableA (ColumnA) VALUES('1')
INSERT INTO #TableA (ColumnA) VALUES('2')
INSERT INTO #TableA (ColumnA) VALUES('3')
INSERT INTO #TableB (ColumnB) VALUES('1')
SELECT *
FROM #TableA
WHERE ColumnA IN(SELECT ColumnA FROM #TableB)
Output:
ColumnA
1
2
3
ColumnA does not exists on #TableB, how come no error is generated?
@@VERSION tells me I’m running this in:
Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (X64) Jul 9 2008 14:17:44 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (VM)
ColumnAin the subquery(SELECT ColumnA FROM #TableB)
refers to theColumnAof #TableA which is a valid column in SELECT list.Hence there’s no error and you get three rows since you are comparing the #TableA.ColumnA with #TableA.ColumnA
If you want to verify the above statement replace ColumnA with anything but other than a valid column (e.g ColumnAB) you will get an error.
If you try this:
the output will be