← Back to PostgreSQL, page 1

postgresql-0020 · Easy fresher

Delete rows that match another table with DELETE ... USING, and compare it with NOT EXISTS.

DELETE FROM target USING other WHERE condition deletes target rows that have a matching row in other. To delete rows without a match, use WHERE NOT EXISTS (subquery). Both can RETURNING the removed rows, and running inside a transaction allows checking the count before committing.

Full answer

Sample schema and data:

sql
CREATE TABLE sessions (id int, user_id int);
CREATE TABLE banned (user_id int);
CREATE TABLE users (id int);
INSERT INTO users VALUES (1), (2), (3);
INSERT INTO sessions VALUES (10, 1), (11, 2), (12, 2), (13, 4);
INSERT INTO banned VALUES (2);
sql
DELETE FROM sessions s USING banned b WHERE b.user_id = s.user_id RETURNING s.id;

Result:

text
 id
----
 11
 12
(2 rows)
sql
DELETE FROM sessions s WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = s.user_id) RETURNING s.id, s.user_id;

Output:

text
 id | user_id
----+---------
 13 | 4
(1 row)
sql
SELECT id, user_id FROM sessions;

PostgreSQL returns:

text
 id | user_id
----+---------
 10 | 1
(1 row)

The USING form removes both sessions of the banned user 2. The NOT EXISTS form removes session 13, whose user 4 does not exist, which is the usual clean-up for orphaned rows. Only session 10 remains. NOT IN (SELECT user_id ...) would behave badly if the subquery returned a NULL, which is why NOT EXISTS is the safer habit. For large deletes, batch the work so locks and WAL volume stay manageable.

sql
CREATE TABLE sessions (id int, user_id int);
CREATE TABLE banned (user_id int);
CREATE TABLE users (id int);
INSERT INTO users VALUES (1), (2), (3);
INSERT INTO sessions VALUES (10, 1), (11, 2), (12, 2), (13, 4);
INSERT INTO banned VALUES (2);

DELETE FROM sessions s USING banned b WHERE b.user_id = s.user_id RETURNING s.id;

DELETE FROM sessions s WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = s.user_id) RETURNING s.id, s.user_id;

SELECT id, user_id FROM sessions;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • DELETE ... USING joins for deletion
  • NOT EXISTS deletes unmatched rows
  • RETURNING lists removed rows
  • Avoid NOT IN with nullable subqueries
  • Batch large deletes

Common mistakes

  • Using NOT IN with a nullable column
  • Deleting millions of rows in one statement at peak time

Follow-ups

  • How would you delete in batches of 10,000?
  • When is TRUNCATE better?

Tips

  • Show the orphan clean-up