Delete from table A if matching row exists in B

Delete from table A if matching row exists in B

I am using SQL. I have two tables: A and B. A has the field email and others. B also has the field email and others. I need to eliminate some records of A depending on if these records also occur in B. How can I do this by keeping the table B untouched?

    Requires Free Membership to View

    By submitting your registration information to SearchSQLServer.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchSQLServer.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

When you delete rows from table A, no deletions will occur in table B unless you have specifically created, in table B, a foreign key with the ON DELETE CASCADE property, that references the primary key of A.

Assuming you haven't done that, the following query will delete matched rows from table A:

delete
  from tableA
 where exists
       ( select 1 
           from tableB
          where email = tableA.email )

This should work in all databases.

Some databases have their own specific DELETE syntax. In Microsoft SQL Server, for example, you could also say:

delete tableA
  from tableA
inner 
  join tableB 
    on tableA.email = tableB.email

This accomplishes the same result; rows are deleted from table A only.

This was first published in January 2005