Search code examples
sqlsql-serversyntax-errorsql-in

How to prevent SQL Server bug in inner select expression (using 'IN' & 'EXISTS' keywords)


I have two different tables with their different columns as below:

CREATE TABLE T1(C1 INT)
CREATE TABLE T2(C2 INT)

Every programmer knows if we write a query with wrong syntax, query compiler should give us an error. Such as this one:

SELECT C1 FROM T2 
--ERROR: Invalid column name 'C1'.

But if we use this wrong query as inner select, unfortunately SQL will execute it:

SELECT * 
FROM T1
WHERE C1 IN (SELECT C1 FROM T2) 
--returns all rows of T1

And also the following wrong query will execute too and returns all rows of T1

SELECT * 
FROM T1
WHERE EXISTS (SELECT C1 FROM T2) 
--returns all rows of T1

It gets worse when we use these wrong queries in UPDATE such as:

UPDATE T1
SET C1 = NULL
WHERE C1 IN (SELECT C1 FROM T2) 
--updates all rows of T1

Now, I want to prevent this bug. I can force my DB developers to be careful but is there any systematic way to prevent this bug?


Solution

  • Ever heard of Correlated Subquery, you can always refer outer query columns inside the subquery

    am sure you must have seen queries like this

    SELECT * FROM T1 
    WHERE EXISTS (SELECT 1 FROM T2 where t1.c1 = t2.c2) 
    

    here C1 column from T1 is referred in Where clause, you are referring in Select thats the difference. There is no BUG here