In Active Record, why does Doctor.left_joins(:appointments).where(appointments: { starts_at: week }) drop doctors with no appointments, and how do you keep them?
answer
- WHERE runs after the outer join
- NULL fails the BETWEEN
- the condition belongs in ON
- scoped association carries it into ON
- string join for full control
basics
~20 sThe LEFT OUTER JOIN keeps doctors with NULL appointment columns, but the WHERE on appointments.starts_at then rejects those NULL rows, so the query behaves like an inner join. Put the date condition in the ON clause, for example through a scoped association.
solid answer
~50 sA LEFT OUTER JOIN pads doctors that have no matching appointment with NULLs, and only then does WHERE run; `appointments.starts_at BETWEEN ...` is not true for NULL, so exactly the doctors you wanted to keep are filtered out, and the result equals `joins`. The condition has to live in the join's `ON` clause. In Rails the clean way is a scoped association, `has_many :appointments_this_week, -> { where(starts_at: Time.current.all_week) }, class_name: "Appointment"`, whose scope Active Record adds to `ON` when you write `left_joins(:appointments_this_week)`. The alternatives are a hand-written `joins("LEFT JOIN appointments ON ... AND appointments.starts_at BETWEEN ...")` with sanitized values, or an `OR appointments.id IS NULL` branch, which only works if no doctor has appointments solely in other weeks. Typical uses are "every doctor with this week's appointment count, including zero" and "doctors free this week".
code
ruby · 15 linesclass Doctor < ApplicationRecord
has_many :appointments
has_many :appointments_this_week,
-> { where(starts_at: Time.current.all_week) },
class_name: "Appointment"
end
# wrong: behaves like an inner join
Doctor.left_joins(:appointments)
.where(appointments: { starts_at: Time.current.all_week })
# right: the date filter sits in ON, every doctor is kept
Doctor.left_joins(:appointments_this_week)
.group("doctors.id")
.select("doctors.*, COUNT(appointments.id) AS week_count")go deeper
Know that left_joins keeps records without matches, and that a where on the joined table's columns can remove them again.
Explain the join-then-WHERE order and why NULL rows fail the condition, and move the condition into ON with a scoped association.
Catch left joins filtered in WHERE during review, write fixtures that include the zero and other-week cases, and choose between scoped associations and string joins.
Name report semantics ('including zero', 'none this week') explicitly in query objects, so the join type and condition placement follow from a stated requirement.
## Order of operations SQL evaluates the join before the WHERE clause: 1. `FROM doctors LEFT OUTER JOIN appointments ON appointments.doctor_id = doctors.id` keeps **every** doctor; one with no appointments gets a row whose `appointments.*` columns are all NULL. 2. `WHERE appointments.starts_at BETWEEN :monday AND :sunday` is then checked per row. For a NULL `starts_at` the comparison is not true, so the row is discarded. ```ruby Doctor.left_joins(:appointments).where(appointments: { starts_at: Time.current.all_week }) # LEFT OUTER JOIN appointments ON appointments.doctor_id = doctors.id # WHERE appointments.starts_at BETWEEN ... AND ... # => same doctors as joins(:appointments) with that where ``` Any WHERE condition that is false or unknown for NULL, which is almost every condition on the joined table's columns, turns a left join back into an inner join. The outer join cost is paid and nothing is gained. ## Putting the condition in ON The condition must filter **which appointments join**, not which rows survive. Three ways in Rails: ### 1. A scoped association (preferred) ```ruby class Doctor < ApplicationRecord has_many :appointments has_many :appointments_this_week, -> { where(starts_at: Time.current.all_week) }, class_name: "Appointment" end Doctor.left_joins(:appointments_this_week) # LEFT OUTER JOIN appointments # ON appointments.doctor_id = doctors.id # AND appointments.starts_at BETWEEN ... AND ... ``` When Active Record joins an association, its scope is added to the `ON` clause. Doctors without this week's appointments survive with NULLs, which is exactly what a "including zero" report needs. The lambda is evaluated each time the query is built, so "this week" stays current. ### 2. A string join `joins("LEFT JOIN appointments ON appointments.doctor_id = doctors.id AND appointments.starts_at >= '...'")` gives full control. Any value in it must be sanitized, never interpolated from input; the sanitizing helpers are a separate topic. ### 3. An IS NULL escape hatch, and why it is wrong here `where(appointments: { starts_at: week }).or(...where(appointments: { id: nil }))` keeps doctors with **no appointments at all**, but still drops doctors whose appointments are all in other weeks: they have joined rows, none matching, and none NULL. It answers a different question. ## How Rails builds the ON clause When a relation joins an association, Active Record assembles the join condition from the reflection: 1. the **key equality**, `appointments.doctor_id = doctors.id`, from the foreign and primary keys; 2. the **association scope**, here `starts_at BETWEEN ...`, merged into the same `ON`; 3. the target model's own **default scope**, if it has one; 4. a **type condition** when the target uses single-table inheritance. Everything in that list filters which appointments join. Conditions you add with `where` afterwards filter which rows survive, which is the distinction this whole bug turns on. ## Typical reports | Report | Relation | |---|---| | every doctor with this week's appointment count, zeros included | `left_joins(:appointments_this_week)` plus a grouped count | | doctors with no appointment this week | `left_joins(:appointments_this_week).where(appointments_this_week: { id: nil })`, or the existence helper for missing associations | | doctors with at least one this week | `joins(:appointments_this_week)` (an inner join is correct here) | In the second row the hash key is the association name; Rails then aliases the joined `appointments` table to `appointments_this_week`, so the `id IS NULL` check targets the outer-joined rows. Checking `to_sql` confirms which table name the WHERE refers to. ## Spotting the bug in review - A `left_joins` followed by a `where` on the joined table's non-key columns is almost always this bug. - Tests usually miss it because fixtures give every doctor an appointment this week. Add a doctor with appointments only in another week, and one with none. - If the outer join is truly unnecessary, switch to `joins` and make the intent explicit.
- Why does adding OR appointments.id IS NULL not fully fix the left join?It keeps doctors with no appointments at all, but a doctor whose appointments all fall in other weeks has joined rows, none of which match the week and none of which are NULL, so that doctor still disappears. Only a condition in the ON clause keeps every doctor.
- How would you test for this bug?Build fixtures or factories with three doctors: one with an appointment this week, one whose appointments are all in another week, and one with none. Assert that a "this week, including zero" query returns all three. The usual fixture set, where every doctor is busy this week, cannot tell the right query from the wrong one.
- left_joins keeps every parent whatever the where clause says
- Rails moves where conditions on joined tables into the ON clause
- OR appointments.id IS NULL keeps every doctor without a matching appointment
- A scoped association's condition is applied after the join in WHERE
- Switching to includes is the fix for a left join filtered in WHERE