SQL Delete clears the table instead of erroring

☆樱花仙子☆ 提交于 2019-12-01 06:34: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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!