I have a piece of SQL which (you would think) wouldn’t compile, but which instead deletes all rows from the target table.
Consider this setup:
create table TableA (ColumnA varchar(200));
create table TableB (ColumnB varchar(200));
insert TableA values ('A'),('B'),('C');
insert TableB values ('A');
Then the following sql:
--Returns all rows from TableA
select * from TableA;
--Does not error (ColumnA does not exist on TableB)
delete TableA where ColumnA in (select ColumnA from TableB)
--No Rows are returned
select * from TableA;
The delete statement above causes all rows to be removed from TableA, rather than erroring that ColumnA doesn’t exist in TableB
There’s a SQL Fiddle demontrating this here: http://www.sqlfiddle.com/#!3/9d883/6
It seems that the ColumnA from TableA is being picked up, but expected it to be “out of scope”.
Why is this?
That works as expected, due to the correlation between ColumnA in the inner query to the outer.
This commonly used correlated query pattern is valid
It removes TableA entries that don’t have a dependent record in TableB.
It shows that you can reference TableA columns in a correlated query. In your query
The inner query is producing
So the DELETE goes through