I am wanting to delete records from a table if multiple columns in this table are in another table.
Currently, I usually just concatenate the columns and use the WHERE IN method:
DELETE FROM TableA
WHERE Col1+Col2 IN (SELECT Col1+Col2 FROM TableB)
Is there a better way to achieve the same result?
Thanks.
Best Answer
Typically, you'd want to join to the two tables together, and delete rows from TableA that match rows in TableB. Something like this:
Using the method you show in your question might result in the wrong rows being deleted. Here's an example to show what I mean:
First, we'll see what values are in both tables:
The intention would be to delete the bottom row, while retaining the top row, in TableA. However, if we run this:
We'll see both rows are gone from TableA.
This statement, however, results in only the correct row being removed from TableA:
Results: