delete where not in another table

From: "Campbell, Lance" <lance(at)illinois(dot)edu>
To: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: delete where not in another table
Date: 2013-07-09 19:25:14
Message-ID: B75CD08C73BD3543B97E4EF3964B7D701F353B73@CITESMBX1.ad.uillinois.edu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

If I have two tables, T1 and T2, such that both have the same primary key of "user_id".
What is the SQL I would use to delete all rows from T1 that are not in T2?

This is one way to write the SQL but it is really inefficient:

DELETE FROM T1 WHERE T1.user_id NOT IN (SELECT user_id FROM T2 WHERE T2.user_id=T1.user_id);

I was thinking there should be a way to write this with a join.

Thanks,

Lance Campbell
Software Architect
Web Services at Public Affairs
217-333-0382
[University of Illinois at Urbana-Champaign logo]<http://illinois.edu/>

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Igor Neyman 2013-07-09 20:36:56 Re: delete where not in another table
Previous Message David Johnston 2013-07-08 23:25:12 Re: Update a composite nested type variable