WHERE IN (SELECT NonExistingColumnName) causes unexpected behavior

Recently, I had a situation where I needed to delete several rows from a table and write the column name incorrectly. The error was not reset, and ALL rows were deleted from the table. Here is a script that reproduces the problem.

There is an order table with four orders with OrderID. There is a table LIST_TO_DELETE with one ItemID.

I had to use

DELETE TOP(1) FROM #Orders WHERE OrderID IN (SELECT ItemID FROM #LIST_TO_DELETE  )

instead i used

DELETE TOP(1) FROM #Orders WHERE OrderID IN (SELECT OrderID FROM #LIST_TO_DELETE  )

This led to deleting all the rows in the #Orders table when I only wanted to delete it.

CREATE TABLE #Orders (OrderID INT, OrderName VARCHAR(100))
INSERT INTO #Orders(OrderID, OrderName) VALUES (1,'Order One'),(2,'Order Two'),(3,'Order Three'), (4,'Order Four')

CREATE TABLE #LIST_TO_DELETE (ItemID INT);INSERT INTO #LIST_TO_DELETE(ItemID) VALUES (1)

DECLARE @rowcount INT = 1
WHILE @rowcount > 0 
BEGIN
    DELETE TOP(1) FROM #Orders WHERE OrderID IN (SELECT OrderID FROM #LIST_TO_DELETE  )
    SET @rowcount = @@rowcount
END 

SELECT * FROM #Orders

DROP TABLE #Orders
DROP TABLE #LIST_TO_DELETE

In my source code, the order table was real, and LIST_TO_DELETE was a table variable, but it doesn't seem to matter what type of table is used. If I use any column name except OrderID or ItemID, I get an error

DELETE TOP(1) FROM #Orders WHERE OrderID IN (SELECT OtherID FROM #LIST_TO_DELETE  )
 Invalid column name 'OtherID'

?

+6
2

, , :

, , FROM . , FROM , , FROM .

+4

.

delete users:

DELETE FROM users WHERE user_id IN (SELECT user_id FROM groups);

user_id.

, , :

DELETE FROM users WHERE user_id IN (SELECT g.user_id FROM groups g);

Msg 207, Level 16, State 1, Line 1
Invalid column name user_id

DELETE TOP(1) FROM #Orders WHERE OrderID IN (SELECT OtherID FROM #LIST_TO_DELETE  )
 Invalid column name 'OtherID'

, OtherID #Orders

+5

All Articles