27
votes

I need to delete rows from an SQLite table where their row IDs do not exist in another table. The SELECT statement returns the correct rows:

SELECT * FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL;

However, the delete statement generates an error from SQLIte:

DELETE FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL;

The error is: SQLite Error 1 - near "left": syntax error. Is there another syntax I could use?

3
To explain: I am deleting rows from the "main" table using an additional where condition, to preserve any rows user has marked as "locked" (i.e., should not be deleted until unlocked): DELETE FROM main WHERE id = ? AND locked = 0; Each successful delete must be followed by deleting a matching row from the "cache" table, but SQlite does not return a value that would let me know whether the first delete statement actually matched any rows. So instead I tried to delete "unmatched" rows from the cache table, and snagged on the left join. - Marek Jedliński

3 Answers

49
votes

SQLite apparently doesn't support joins with the delete statement, as you can see on the Syntax diagrams. You should however be able to use a subquery to delete them.

ie.

DELETE FROM cache WHERE id IN
(SELECT cache.id FROM cache LEFT JOIN main ON cache.id=main.id WHERE main.id IS NULL);

(Not tested)

18
votes

Since you going down the route of subquery, might as well get rid of the join altogether and simplify the query:

DELETE FROM cache WHERE id NOT IN (SELECT id from main);
0
votes

Solution from @wimvds didn't work for me, so I modified the query and removed WHERE condition:

DELETE FROM FirstTable WHERE firstTableId NOT IN (SELECT SecondTable.firstTableId FROM SecondTable LEFT JOIN FirstTable ON FirstTable.firstTableId=SecondTable.firstTableId)

This deletes all the rows from FirstTable that do not have their id assigned to any row in SecondTable.