SQL Delete clears the table instead of erroring

后端 未结 2 1342
抹茶落季
抹茶落季 2021-01-13 00:55

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:

creat         


        
相关标签:
2条回答
  • 2021-01-13 01:32

    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

    DELETE TableA WHERE NOT EXISTS (select * from TableB where TableB.ID=TableA.ID)
    

    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

    delete TableA where ColumnA in (select ColumnA from TableB)
    

    The inner query is producing

    • one row for each record in TableB
    • one column for each row, whose value is ColumnA from outer query

    So the DELETE goes through

    0 讨论(0)
  • 2021-01-13 01:50

    While I understand the confusion, it is behaving as it should. ColumnA is still "in scope". In fact you could join on it in your subquery if you wanted. The brackets don't limit the scope, but from a readability standpoint I can see the confusion that it creates.

    This is another example of why it's a good idea to always prefix your column names with the table name (or alias).

    0 讨论(0)
提交回复
热议问题