Skip to main content

DELETE with JOIN in ActiveRecord

How delete_all with joins is rewritten on PostgreSQL, when to use DELETE USING, and how to remove rows with no children.

R
Raza Hussain
· 7 min read · 3
A cracked stone block with a Rails delete_all join snippet on top and the generated DELETE FROM posts subquery below.

Rails has no DELETE … JOIN. When you call delete_all on a relation with joins, ActiveRecord rewrites it to DELETE FROM posts WHERE posts.id IN (SELECT posts.id FROM posts INNER JOIN ...). It works on PostgreSQL, skips every callback, and returns the number of rows deleted. You write the join once and Rails builds the subquery for you.

Tested with ActiveRecord 8.1.1, PostgreSQL 16.15 and Ruby 3.3.6. Every query and result below comes from the test script. The SQL rewrite was observed on PostgreSQL only. I did not run these on MySQL or SQLite.

The SQL you start with

You want to delete posts written by banned authors. In PostgreSQL the native form is DELETE ... USING:

DELETE FROM posts
USING authors
WHERE authors.id = posts.author_id
  AND authors.banned = true

MySQL writes DELETE posts FROM posts JOIN authors .... Neither form exists in ActiveRecord’s query interface. The converter at sqltoactiverecord.com covers the SELECT side of joins. For deletes you need the pattern below.

delete_all with joins

Post.joins(:author).where(authors: { banned: true }).delete_all

The log shows what Rails sends:

DELETE FROM "posts" WHERE ("posts"."id") IN (
  SELECT "posts"."id" FROM "posts"
  INNER JOIN "authors" ON "authors"."id" = "posts"."author_id"
  WHERE "authors"."banned" = $1
)

The result was 1 deleted row, and the two posts by the other author stayed. Rails does not emit USING. It moves the whole relation, joins included, into an IN subquery on the primary key. The outer DELETE then touches only the target table.

This has three consequences.

  • The rewrite selects posts.id, so the model needs its primary key.
  • The join runs in the subquery, so the planner decides how to execute it. For large deletes read the plan before you trust it.
  • delete_all returns the affected row count, not the records.

Callbacks and dependent options are skipped

delete_all never instantiates models. I put a before_destroy callback on Post and ran both versions.

Post.joins(:author).where(authors: { banned: true }).destroy_all
# SELECT posts.* ... INNER JOIN authors ...
# [callback] before_destroy ran
# BEGIN
# DELETE FROM "posts" WHERE "posts"."id" = $1
# COMMIT

Post.joins(:author).where(authors: { banned: true }).delete_all
# one DELETE ... IN (SELECT ...), no callback output

destroy_all loads each row, runs callbacks, and issues one DELETE per record inside its own transaction. delete_all runs one statement and nothing else. This also means dependent: :destroy on associations does not fire and counter_cache counters on the parent do not decrement, because both live in callbacks. I tested both. With has_many :comments, dependent: :destroy on Post, the joined delete_all left the banned post’s comment row behind as an orphan. With belongs_to :author, counter_cache: true, the author’s posts_count stayed at 1 after its only post was deleted, while destroy_all ran the decrementing UPDATE. A foreign key from posts.author_id to authors without ON DELETE CASCADE made PostgreSQL reject deleting an author that still had posts, and Rails raised ActiveRecord::InvalidForeignKey. For the full comparison read destroy_all vs delete_all. This post does not repeat it.

Delete rows with no children

The common real use is cleaning orphans: posts with zero comments. where.missing builds the anti-join for you.

Post.where.missing(:comments).delete_all
DELETE FROM "posts" WHERE ("posts"."id") IN (
  SELECT "posts"."id" FROM "posts"
  LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
  WHERE "comments"."id" IS NULL
)

With three posts, one without comments, it deleted 1 row and left p1 and p2. The hand-written form gives identical SQL:

Post.left_joins(:comments).where(comments: { id: nil }).delete_all

Both produce the same statement in the log, character for character. If you prefer a subquery over a join, see EXISTS and NOT EXISTS in Rails. The left join version has the trap described in left join where in ActiveRecord: put the null check on the joined table, never a value filter, or you turn the outer join into an inner one.

When to write DELETE USING yourself

Rails rewrites to IN (subquery). The extra join has a cost. On 500,000 posts with 50,000 matching rows, EXPLAIN (ANALYZE) on PostgreSQL 16.15 showed the Rails form as a Hash Semi Join that scans posts twice (180.6 ms). The DELETE ... USING form scanned posts once (60.7 ms). Each figure is the third of three runs, rolled back, on one machine, so treat the ratio as a hint and run EXPLAIN on your own data. Write raw SQL when you want a specific plan, a RETURNING clause, or multiple joined tables with USING.

n = Post.connection.exec_delete(<<~SQL)
  DELETE FROM posts USING authors
  WHERE authors.id = posts.author_id AND authors.banned = true
SQL
# n => 1

exec_delete returned 1 in my run. The raw form skips the model layer completely, so scopes and callbacks defined on the model play no part. Any scope you rely on has to be written into the SQL.

For RETURNING, use select_all:

Post.connection.select_all(
  "DELETE FROM posts USING authors WHERE authors.id = posts.author_id AND authors.banned RETURNING posts.id"
)

Call .to_a on the result to get hashes. In my run it returned [{"id" => 37, "title" => "p_bad"}], the one deleted row. PostgreSQL documents RETURNING and USING on DELETE.

Traps I hit while testing

  • limit works with joins and delete_all. The limit lands inside the subquery: ... WHERE authors.banned = $1 LIMIT $2. It deleted 1 row. Without an ORDER BY you do not control which row goes. Add an order.
  • group and having with delete_all also run. Rails put GROUP BY posts.id HAVING (count(*) > 0) inside the subquery. No error, but read the SQL before running it on production data.
  • On an association, author.posts.joins(:comments).delete_all adds posts.author_id = $1 to the same subquery and deleted 1 row.
  • to_sql on the relation shows the SELECT form, not the DELETE. To see the DELETE, turn on the logger or read the development log.

Scale limits

A single DELETE of millions of rows holds locks for the whole statement, writes a large volume of WAL, and leaves dead tuples for autovacuum. The join subquery adds read cost on top. Delete in batches by primary key range or use in_batches:

Post.where.missing(:comments).in_batches(of: 5_000) do |batch|
  batch.delete_all
end

I ran this pattern with of: 1 on a small table and read the SQL. Rails selects the next batch of ids in primary key order, then sends one DELETE ... IN (subquery) per batch with the batch condition added inside the subquery. I did not benchmark it. Pick the batch size by watching lock time and replication lag on your own system. If you delete the same data every night, consider partitions and dropping a partition, which avoids row deletes entirely.

Which form to use

Need Use
Callbacks must run destroy_all on the joined relation
Fast delete, no callbacks joins(...).delete_all
Orphan cleanup where.missing(:assoc).delete_all
RETURNING or multi-table USING raw SQL with exec_delete or select_all

Sources: PostgreSQL DELETE, ActiveRecord::Relation#delete_all, ActiveRecord::Batches#in_batches, WhereChain#missing.

The same join-to-subquery rewrite applies to updates, see UPDATE with JOIN in Rails. To turn your own DELETE or JOIN into ActiveRecord, paste it into the join converter.

Related: destroy_all vs delete_all, EXISTS and NOT EXISTS in Rails, left join where trap

Frequently asked questions

How does ActiveRecord delete_all work with joins?
Rails moves the joined relation into a subquery and runs DELETE FROM posts WHERE posts.id IN (SELECT posts.id ... INNER JOIN ...). In my PostgreSQL 16 test it returned the number of deleted rows.
Does delete_all with joins run callbacks?
No. destroy_all on the same joined relation ran the before_destroy callback, while delete_all sent one DELETE statement and ran no callback.
How do I delete records that have no children?
Use Post.where.missing(:comments).delete_all. Rails builds a LEFT OUTER JOIN with comments.id IS NULL inside an IN subquery, identical to left_joins plus where(comments: { id: nil }).
Does Rails generate DELETE USING on PostgreSQL?
No. In my test it always generated DELETE ... WHERE id IN (subquery). Use exec_delete with raw SQL if you need DELETE USING or RETURNING.
Can I combine limit with delete_all and joins?
Yes. The LIMIT lands inside the subquery and my test deleted one row. Add an order, or you do not control which row goes.
Is delete_all with joins slower than DELETE USING?
In my PostgreSQL 16.15 test on 500,000 posts, the Rails IN subquery took 180.6 ms and DELETE USING took 60.7 ms, because the subquery form scans the posts table twice. One machine, one dataset, so run EXPLAIN on your own data.

Was this article helpful?

Your feedback helps us improve our content

Be the first to vote!

How We Verify Conversions

Every conversion shown on this site follows a strict verification process to ensure correctness:

  • Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
  • Check generated SQL with to_sql — We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.)
  • Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
  • Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility

Last updated: December 03, 2026

Try These Queries in Our Converter

See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.

3

Leave a Response

Responses (0)

No responses yet

Be the first to share your thoughts

R

Raza Hussain

Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.

💼 15 years experience 📝 66 posts