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.
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
jsoncolumn on the parent table raisescould not identify an equality operator for type json.jsonbcolumns can be compared, so they don’t hit this. -
An
orderon a joined column that is not in the select list raisesfor 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
- Look at the association path, not today’s counts. If the join goes through any to-many association, it can fan out.
rel.countequal torel.distinct.counttoday only means no parent has two matching children yet. - Never
SUMorAVGa parent column over a join to its children, and do not reach fordistinct.sum(it sums distinct values). Aggregate per table, for examplePost.group(:author_id).sum(:views). - To filter parents by their children, use
where(id: Child.where(...).select(:parent_id))orEXISTS, not ajoinschain plusdistinct. - Pass relations (
select(:id)), notplucked arrays, so the filter stays one SQL statement. - 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
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.
Deep Dive into ActiveRecord
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.
More on SQL to ActiveRecord
ActiveRecord where vs find_by — Which to Use When
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
Rails Counter Cache—When Posts.count Brought Down Production
posts.count hit the database on every request and brought down production. Here's how counter cache fixes it, what to watch for, and how to backfill safely.
SQL Certification on Resume. Rails Interview Failed. Knew Databases. Didn't Know ActiveRecord.
I had SQL certification on my resume and failed a Rails interview. Knowing databases and knowing ActiveRecord are two different skills. Here's the gap.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts