I have two tables in a PostgreSQL 9.3 database: Table link_reply
has a foreign key named which_group
pointing to table link_group
.
I want to delete all rows from link_group
where no related row in link_reply
exists. Sounds basic enough but I've been struggling with it.
Will it be something simple like this (not working)?
DELETE FROM link_group WHERE link_reply = NULL;
Best Answer
Quoting the manual:
Bold emphasis mine. Using information that is not contained in another table is a tad bit tricky, but there are easy solutions. From the arsenal of standard techniques to ...
... a
NOT EXISTS
anti-semi-join is probably simplest and most efficient forDELETE
:Assuming (since table definitions are not provided)
link_group_id
as column name for the primary key oflink_group
.The technique @Mihai commented works as well (applied correctly):
But since the table expression in the
USING
clause is joined to the target table (lg
in the example) with aCROSS JOIN
, you need another instance of the same table as stepping stone (lg1
in the example) for theLEFT JOIN
, which is less elegant and typically slower.