Skip to main content

Rails Joins Return Duplicate Rows? Rewrite Them as Subqueries

Chaining joins through has_many tables multiplies rows and inflates COUNT and SUM. Tested rewrites with where(id: subquery) and EXISTS, with EXPLAIN times.

R
Raza Hussain
· Updated: · 8 min read · 592
A row of repeated author blocks under the headline Joins multiply rows, with the label Filter with subqueries

You chain joins across several has_many associations to filter parents by their children. The query returns far more rows than there are parents, count is wrong, and adding distinct makes it slow or makes it fail. The cause is join fan-out, and the usual fix is to filter with a subquery instead of a join.

How this was tested

Every number below came from one script: ActiveRecord 8.1.1 against PostgreSQL 15.10 on a laptop, with default settings (work_mem 4MB, shared_buffers 128MB). The data was generated as 5,000 authors, 50,000 posts, 400,000 comments, 50 tags and 150,000 taggings:

INSERT INTO authors (name) SELECT 'a' || g FROM generate_series(1, 5000) g;
INSERT INTO posts (author_id, views) SELECT (g % 5000) + 1, 10 FROM generate_series(1, 50000) g;
INSERT INTO comments (post_id, flagged) SELECT (g % 50000) + 1, g % 50 = 0 FROM generate_series(1, 400000) g;
INSERT INTO taggings (post_id, tag_id) SELECT (g % 50000) + 1, (g % 50) + 1 FROM generate_series(1, 150000) g;
ANALYZE;

The indexes are the primary keys plus the ones t.references creates: posts.author_id, comments.post_id, taggings.post_id and taggings.tag_id. There is no index on comments.flagged.

The timings are EXPLAIN (ANALYZE) execution times: the median of 5 runs, with a warm cache. They show the size of the difference on this machine, not what your production database will do.

The query

The models are Author has_many :posts, and Post has_many :comments and has_many :taggings. The question is: which authors have a post that has a flagged comment and carries tag 1?

Author.joins(posts: [:comments, :taggings])
      .where(comments: { flagged: true }, taggings: { tag_id: 1 })
SELECT "authors".* FROM "authors"
INNER JOIN "posts" ON "posts"."author_id" = "authors"."id"
INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
INNER JOIN "taggings" ON "taggings"."post_id" = "posts"."id"
WHERE "comments"."flagged" = TRUE AND "taggings"."tag_id" = 1

It returned 24,000 rows for 100 distinct authors. An INNER JOIN emits one row for every combination of matching rows. An author appears once for each pair of matching comment and tagging across each matching post. That is fan-out: every to-many association in the chain multiplies the row count. That covers has_many, has_many :through, has_and_belongs_to_many, and a has_one whose foreign key has no unique index.

Why count and SUM go wrong

count on the joined relation counts joined rows, not authors:

rel = Author.joins(posts: [:comments, :taggings])
            .where(comments: { flagged: true }, taggings: { tag_id: 1 })
rel.count           # => 24000
rel.distinct.count  # => 100

Aggregates over a parent column are multiplied the same way. For one author with 10 posts of 10 views each:

author.posts.sum(:views)                                                # => 100
Author.where(id: author.id).joins(posts: :comments).sum("posts.views")  # => 800

Each post’s views was added once per comment. No error is raised. The number is simply wrong.

distinct does not fix it. distinct.sum("posts.views") becomes SUM(DISTINCT "posts"."views"), which adds each distinct value once. For this author it returned 10, because all ten posts had the same 10 views. Aggregate per table instead:

Post.where(author_id: author_ids).group(:author_id).sum(:views)
# => {1 => 100, 2 => 100}

Fix 1: distinct, which works only sometimes

rel.distinct

This returned the 100 authors, but the plan shows the cost. PostgreSQL built all 24,000 joined rows, sorted them, and removed duplicates:

Unique  (actual rows=100)
  ->  Sort  (actual rows=24000)
        ->  Nested Loop  (actual rows=24000)

The median execution time was 23.3 ms. Loading the plain join without distinct into Ruby took about 97 ms of wall-clock time in one run, mostly building 24,000 Author objects for 100 authors. That is a Ruby-side measurement, so it is not in the table below.

SELECT DISTINCT "authors".* also fails outright in two common cases on PostgreSQL. Both were reproduced in the same script:

  • A json column on the parent table raises could not identify an equality operator for type json. jsonb columns can be compared, so they don’t hit this.
  • An order on a joined column that is not in the select list raises for SELECT DISTINCT, ORDER BY expressions must appear in select list. One example is .order("posts.created_at").

Both are reasons to filter with a subquery instead.

Fix 2: filter with where(id: subquery)

Ask the question the way it is meant: authors whose id is in the set of matching posts’ author ids.

flagged_post_ids = Comment.where(flagged: true).select(:post_id)
tagged_post_ids  = Tagging.where(tag_id: 1).select(:post_id)

Author.where(
  id: Post.where(id: flagged_post_ids)
          .where(id: tagged_post_ids)
          .select(:author_id)
)

ActiveRecord nests the relations as IN (SELECT ...) and sends one query:

SELECT "authors".* FROM "authors"
WHERE "authors"."id" IN (
  SELECT "posts"."author_id" FROM "posts"
  WHERE "posts"."id" IN (SELECT "comments"."post_id" FROM "comments" WHERE "comments"."flagged" = TRUE)
    AND "posts"."id" IN (SELECT "taggings"."post_id" FROM "taggings" WHERE "taggings"."tag_id" = 1)
)

It returned the same 100 author ids as the distinct join, with a median of 4.9 ms. No row is multiplied: each author row is either in the result or not. It also works with json columns and with any order on authors.

Pass the relation with select(:column), not pluck. pluck runs a separate query and pastes the ids into the SQL as a literal list. A relation stays a single subquery. More subquery patterns are on the SQL subquery to ActiveRecord page.

Fix 3: EXISTS

EXISTS states “at least one matching child” directly. ActiveRecord 8.1 has no where.exists: WhereChain only offers not, associated and missing. So build it from relations with arel.exists, and use Arel attributes for the correlation instead of raw SQL strings:

authors, posts = Author.arel_table, Post.arel_table
flagged = Comment.where(Comment.arel_table[:post_id].eq(posts[:id])).where(flagged: true)
tagged  = Tagging.where(Tagging.arel_table[:post_id].eq(posts[:id])).where(tag_id: 1)

Author.where(
  Post.where(posts[:author_id].eq(authors[:id]))
      .where(flagged.arel.exists)
      .where(tagged.arel.exists)
      .arel.exists
)
SELECT "authors".* FROM "authors"
WHERE EXISTS (
  SELECT "posts".* FROM "posts"
  WHERE "posts"."author_id" = "authors"."id"
    AND EXISTS (SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = "posts"."id" AND "comments"."flagged" = TRUE)
    AND EXISTS (SELECT "taggings".* FROM "taggings" WHERE "taggings"."post_id" = "posts"."id" AND "taggings"."tag_id" = 1)
)

It returned the same 100 ids with a median of 4.9 ms. The correlation still names authors and posts by table name. If the outer query aliases those tables, for example in a self-join, point the Arel attributes at the alias.

On this data, IN and EXISTS were equal. Which one wins depends on your data and indexes, so compare both with EXPLAIN (ANALYZE) on a production-sized copy. For the negative case, prefer NOT EXISTS: NOT IN returns no rows when the subquery contains a NULL. The EXISTS page and the post on SQL EXISTS and NOT EXISTS in ActiveRecord cover that case.

Results on the test data

Query Rows returned Correct authors EXPLAIN ANALYZE, median of 5
joins chain 24,000 no (repeats) not run
joins + distinct 100 yes 23.3 ms
where(id: subquery) 100 yes 4.9 ms
EXISTS 100 yes 4.9 ms

Your plan depends on row counts, indexes and settings, so run EXPLAIN (ANALYZE) on your own data before choosing. The EXPLAIN page shows how to get that plan from a relation.

When a join is still the right tool

Keep joins when you select or order by columns of the joined table and each parent has at most one matching row, as through a belongs_to. Fan-out comes from to-many associations. If you need the children’s data too, load it separately with includes or preload rather than widening the join. The joins vs includes page explains which one sends which SQL.

Checklist

  1. Look at the association path, not today’s counts. If the join goes through any to-many association, it can fan out. rel.count equal to rel.distinct.count today only means no parent has two matching children yet.
  2. Never SUM or AVG a parent column over a join to its children, and do not reach for distinct.sum (it sums distinct values). Aggregate per table, for example Post.group(:author_id).sum(:views).
  3. To filter parents by their children, use where(id: Child.where(...).select(:parent_id)) or EXISTS, not a joins chain plus distinct.
  4. Pass relations (select(:id)), not plucked arrays, so the filter stays one SQL statement.
  5. Measure the candidates with EXPLAIN (ANALYZE) on data shaped like production.

Sources: Active Record Query Interface guide, joining tables, PostgreSQL subquery expressions (EXISTS, IN), PostgreSQL SELECT DISTINCT.

Tested conversions for this topic

Each page shows the SQL, the ActiveRecord code, and the SQL Rails actually generated on Rails 8.1.1.

  • ActiveRecord Subquery in Rails Convert a SQL IN (SELECT ...) subquery to Rails ActiveRecord with where(id: relation.select). Tested on Rails 8.1, with the NOT IN NULL trap explained.
  • Find Slow Queries in Rails with PostgreSQL Find slow queries in a Rails app on PostgreSQL: subscribe to sql.active_record, set log_min_duration_statement, then run explain(:analyze) on the worst one.

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.

592

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 📝 63 posts