Ask the Expert

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

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: