11

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?

1
  • 5
    It doesn't delete anything because when link_type.id is null, url.link_type = link_type.id is not true so these two conditions are never satisfied together. Commented Apr 16, 2013 at 10:42

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this query on two tables with 300k, and 600k rows respectively, and the query timed out after 30 minutes.
7

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 );

1 Comment

Because if "url.link_type = link_type.id" is "TRUE" then "link_type.id" is not "NULL", if "link_type.id" is "NULL" the first condition "url.link_type = link_type.id" will returns "NULL" too then you get "NULL AND TRUE" that is just "NULL". Since NULL is a unknow value you cannot say that it is TRUE or FALSE, so no rows is displayed. The NOT EXISTS will to the work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.