delete where not in another table

Поиск
Список
Период
Сортировка
Искать

delete where not in another table

От:
"Campbell, Lance" <lance@illinois.edu>
Дата:

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

 

 

Re: delete where not in another table

От:
Igor Neyman <ineyman@perceptron.com>
Дата:
From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-owner@postgresql.org] On Behalf Of Campbell, Lance
Sent: Tuesday, July 09, 2013 3:25 PM
To: pgsql-sql@postgresql.org
Subject: [SQL] delete where not in another table

  
DELETE FROM T1 WHERE T1.user_id NOT IN (SELECT user_id FROM T2 WHERE T2.user_id=T1.user_id); 
  
Thanks, 
  
Lance Campbell 
Software Architect 
Web Services at Public Affairs 
217-333-0382 

  --
Try: 

DELETE  FROM t1   USING t2  WHERE t1.user_id != t2.user_id;

Test it before running on production db.

Regards,
Igor Neyman
  


Re: delete where not in another table

От:
Marc Mamin <M.Mamin@intershop.de>
Дата:
> Subject: [SQL] delete where not in another table
> DELETE FROM T1 WHERE T1.user_id NOT IN (SELECT user_id FROM T2 WHERE T2.user_id=T1.user_id);


Following query use an anti join and is much faster:
 delete from t1 where not exists (select user_id  from t2 where t2.user_id =t1.user_id )

regards,

Marc Mamin

FAQ