SQL inner query conundrum
by SoftSprocket from LinuxQuestions.org on (#5C31M)
I recently suffered through a minor database disaster. The query I meant to run was something like this
Code:delete from table_a where x_id in (select x_id from table_b where field_a = 2345)What I in fact ran was:
Code:delete from table_a where x_id in (select x_id from table_c where field_a = 2345)Now, table_c didn't have a field x_id but instead of exiting with an error all records were deleted from table_c. We were able to recover using backups and transaction logs.
This was run on SQL Server. I verified the behavior substituting 'select count(*)' for delete.
I was shocked by this since my expectation is that the query would fail however I found this on a Microsoft page discussing subqueries:
Quote:
In the query in question table_a did not have a column named field_a so SQL Server must not only have satisfied the requirement for x_id in the subquery but also ignored the where clause giving
Code:delete from table_a where x_id in (select x_id from table_a)If this is what it does I have to wonder is this an expected SQL Server behavior? A SQL behavior? A bug perhaps?
To me it makes no sense.


Code:delete from table_a where x_id in (select x_id from table_b where field_a = 2345)What I in fact ran was:
Code:delete from table_a where x_id in (select x_id from table_c where field_a = 2345)Now, table_c didn't have a field x_id but instead of exiting with an error all records were deleted from table_c. We were able to recover using backups and transaction logs.
This was run on SQL Server. I verified the behavior substituting 'select count(*)' for delete.
I was shocked by this since my expectation is that the query would fail however I found this on a Microsoft page discussing subqueries:
Quote:
If a column is referenced in a subquery that does not exist in the table referenced by the subquery's FROM clause, but exists in a table referenced by the outer query's FROM clause, the query executes without error. SQL Server implicitly qualifies the column in the subquery with the table name in the outer query. |
Code:delete from table_a where x_id in (select x_id from table_a)If this is what it does I have to wonder is this an expected SQL Server behavior? A SQL behavior? A bug perhaps?
To me it makes no sense.