In Active Record, why does Doctor.joins(:appointments).where(appointments: { starts_at: week }) list a doctor several times, and how do you return each doctor once?
answer
- one row per matching appointment
- SELECT DISTINCT doctors.*
- DISTINCT plus ORDER BY a joined column
- IN (subquery) instead of a join
- count changes along with the rows
basics
~10 sAn INNER JOIN produces one row per matching appointment, and Active Record builds one Doctor object per row. Add .distinct, or filter with where(id: Appointment.where(...).select(:doctor_id)) so the doctors table is never multiplied.
solid answer
~40 s`joins(:appointments)` on a `has_many` yields one SQL row for each doctor-appointment pair that passes the WHERE, and Active Record instantiates a `Doctor` per row, so a doctor with five appointments this week appears five times. Two Rails fixes: `.distinct`, which turns the query into `SELECT DISTINCT doctors.*`, or a subquery filter, `Doctor.where(id: Appointment.where(starts_at: week).select(:doctor_id))`, which returns each doctor once with no join at all. `distinct` has costs: the database compares whole rows, and on PostgreSQL ordering by a joined column such as `appointments.starts_at` fails because `ORDER BY` expressions must appear in a DISTINCT select list. The subquery form also composes with `limit` and pagination without surprises, which is why it is often the better choice for "doctors who have X" lists.
code
ruby · 13 linesweek = Time.current.all_week
# duplicates: one Doctor per matching appointment
Doctor.joins(:appointments).where(appointments: { starts_at: week })
# dedupe the joined rows
Doctor.joins(:appointments).where(appointments: { starts_at: week }).distinct
# no join at all: each doctor once, safe to order and page
Doctor
.where(id: Appointment.where(starts_at: week).select(:doctor_id))
.order(:name)
.limit(20)go deeper
Know that joining a has_many returns the parent once per matching child and that .distinct removes the repeats.
Explain why Rails builds one object per row, compare distinct with a where(id: subquery) filter, and note what each does to ordering and limits.
Pick the dedupe strategy by what the page sorts and pages on, and spot the PostgreSQL DISTINCT-with-ORDER-BY failure before it ships.
Standardise on subquery filters for 'parents that have X' lists so pagination and counts stay correct as queries gain joins.
## Where the duplicates come from A SQL join pairs each doctor row with each matching appointment row. `Doctor.joins(:appointments)` still selects only `doctors.*`, but the **number of rows** is the number of pairs: ```ruby week = Time.current.all_week Doctor.joins(:appointments).where(appointments: { starts_at: week }).map(&:name) # => ["Dr Adams", "Dr Adams", "Dr Adams", "Dr Chen", "Dr Chen"] ``` Active Record builds one `Doctor` object per returned row and does not merge rows that share a primary key, so the same doctor arrives as several separate objects. This only happens when the join can match **many** rows per parent: joining a `belongs_to` cannot multiply the parent, and a `has_one` only does so when the data breaks its one-row assumption. ## Fix 1: distinct ```ruby Doctor.joins(:appointments).where(appointments: { starts_at: week }).distinct # SELECT DISTINCT doctors.* FROM doctors INNER JOIN appointments ... ``` This is the shortest fix, and the Rails guides use it. Its costs: - The database must compare **every selected column** to remove duplicates, after producing all the joined rows. - On PostgreSQL, `.order("appointments.starts_at")` together with `distinct` fails with "for SELECT DISTINCT, ORDER BY expressions must appear in select list", because the sort column is not part of `doctors.*`. - Columns of types that cannot be compared for equality (PostgreSQL's `json`, unlike `jsonb`) make `SELECT DISTINCT doctors.*` fail. ## Fix 2: a subquery instead of a join ```ruby Doctor.where(id: Appointment.where(starts_at: week).select(:doctor_id)) # SELECT doctors.* FROM doctors # WHERE doctors.id IN (SELECT appointments.doctor_id FROM appointments WHERE ...) ``` - The doctors table is never multiplied, so no deduplication is needed. - Ordering by doctor columns and paging with `limit`/`offset` behave as for a plain query. - It reuses `Appointment` scopes directly: `Appointment.confirmed.where(starts_at: week).select(:doctor_id)`. Its limit: you cannot sort by or select appointment columns, since the outer query never sees them. ## Fix 3: group by the parent `group("doctors.id")` also collapses duplicates and lets you aggregate (earliest appointment, number of appointments), which is a calculation question in its own right. ## Choosing | Need | Approach | |---|---| | list doctors who have a matching appointment | subquery with `where(id: ...)` | | quick dedupe, no ordering by appointment columns | `.distinct` | | sort doctors by their next appointment | `group` with an aggregate, or a window query | | doctors plus their appointments for display | an eager-loading call, not `joins` | ## Which joins multiply | Joined association | Rows per parent | |---|---| | `belongs_to` | at most one, no duplicates | | `has_one` | one, as long as the data honours it | | `has_many`, `has_many :through` | one per matching child | | nested `joins(appointments: :patient)` | one per matching appointment-patient pair | | two collections, `joins(:appointments, :reviews)` | the product of both counts | ## Side effects to remember - **Counts change**: a count on the joined relation counts pairs, not doctors, unless the count is distinct. Counting across joins is a separate topic, but the cause is the same. - **Limits are applied to rows, not doctors**: `limit(10)` on the joined relation may return only three distinct doctors. - **Several has_many joins multiply**: `joins(:appointments, :reviews)` returns appointments x reviews rows per doctor, which grows quickly. Reading `to_sql` and asking "how many rows per doctor can this produce?" catches all of these before they reach a page.
- Why does Doctor.joins(:appointments).distinct.order("appointments.starts_at") fail on PostgreSQL?With `SELECT DISTINCT`, PostgreSQL requires every `ORDER BY` expression to appear in the select list, and `appointments.starts_at` is not part of `doctors.*`. Either select it explicitly, group by the doctor with an aggregate such as `MIN(appointments.starts_at)`, or drop the join and filter with a subquery.
- Does joining a belongs_to association duplicate rows?No. `Appointment.joins(:doctor)` matches at most one doctor per appointment, so the number of appointment rows stays the same. Duplication appears only when the joined side can match many rows per parent, as with `has_many` or `has_many :through`.
- Active Record merges rows with the same id into one object
- distinct is always free because the database already has the rows
- Joining a belongs_to association duplicates the child rows
- limit(10) on a has_many join always returns ten distinct doctors
- The subquery form needs distinct to avoid duplicates too