Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete rows using an outer join

I've got a problem to delete records from a PostgreSQL table, using a LEFT JOIN.

I'd like to delete rows I get with the following query:

SELECT * FROM url 
LEFT JOIN link_type ON url.link_type = link_type.id 
WHERE link_type.id IS NULL

To do so, here is what I did:

 DELETE FROM url
 USING link_type
 WHERE url.link_type = link_type.id  AND link_type.id IS NULL

Query works but doesn't delete anything, although that's exactly what's explained in the doc: http://www.postgresql.org/docs/current/static/sql-delete.html.

Is my problem due to IS NULL in the query or Am I missing something?

like image 881
SuN Avatar asked Apr 16 '13 10:04

SuN


2 Answers

Good work, sun. Minor suggestion: when using EXISTS/NOT EXISTS you don't need to SELECT *. A common convention (docs) is to just write SELECT 1 as like this:

DELETE FROM url WHERE NOT EXISTS (
  SELECT 1 FROM link_type WHERE url.link_type = link_type.id 
);

Functionally, both ways work.

like image 160
marcj Avatar answered Sep 17 '22 16:09

marcj


Still don't understand why my previous query doesn't work (if someone could explain, would be nice), but here is how I did the trick:

DELETE FROM url WHERE NOT EXISTS (SELECT * FROM link_type WHERE url.link_type = link_type.id );
like image 24
SuN Avatar answered Sep 18 '22 16:09

SuN