In Active Record, why does Apartment.where.not(pets_policy: "none") leave out apartments whose pets_policy is NULL, and how do you include them?
answer
- three-valued logic in SQL
- != NULL is unknown, not true
- or(where(column: nil)) adds them back
- several keys negate as NAND
- NOT IN with a NULL in the list
basics
~20 swhere.not writes pets_policy != 'none', and for a NULL row that comparison is unknown rather than true, so SQL drops the row. Add the NULLs back with .or(Apartment.where(pets_policy: nil)), or make the column NOT NULL.
solid answer
~40 s`where.not` inverts the predicate the hash would build, so `where.not(pets_policy: "none")` becomes `pets_policy != 'none'`. SQL uses three-valued logic: comparing `NULL` with anything gives unknown, and a WHERE clause keeps only rows where the condition is true, so apartments with no policy silently disappear. To keep them, write `Apartment.where.not(pets_policy: "none").or(Apartment.where(pets_policy: nil))`, which gives `pets_policy != 'none' OR pets_policy IS NULL`; the better long-term fix is a NOT NULL column with a default. Two more traps: with several keys, `where.not(city: "Lyon", furnished: true)` means `NOT (city = 'Lyon' AND furnished = TRUE)` (NAND, since Rails 6.1), not "neither"; and `where.not(id: subquery)` becomes `NOT IN`, which returns nothing if the subquery yields a single NULL.
code
ruby · 12 linesApartment.where.not(pets_policy: "none")
# WHERE pets_policy != 'none' -- NULL rows dropped
Apartment.where.not(pets_policy: "none")
.or(Apartment.where(pets_policy: nil))
# WHERE (pets_policy != 'none' OR pets_policy IS NULL)
Apartment.where.not(city: "Lyon", furnished: true)
# WHERE NOT (city = 'Lyon' AND furnished = TRUE)
Apartment.where(city: "Lyon").excluding(current_apartment)
# WHERE city = 'Lyon' AND id != 42go deeper
Remember that where.not on a nullable column drops the NULL rows, and that where.not(column: nil) is how you write IS NOT NULL.
Explain three-valued logic, the NAND meaning of a multi-key where.not, and how or(where(column: nil)) or a NOT NULL default fixes the missing rows.
Spot NOT IN with nullable subqueries in reviews and replace it with where.missing, and push nullable filter columns toward NOT NULL with defaults.
Treat nullable filter columns as a data-model decision: each one doubles the cases every negative filter has to handle, so pay for the constraint early.
## What where.not actually writes `where` with no arguments returns a `WhereChain`, and `WhereChain#not` builds the condition you pass exactly as `where` would, then **inverts** it. For a single hash key the inversion is per operator: | Call | SQL | |---|---| | `where.not(pets_policy: "none")` | `pets_policy != 'none'` | | `where.not(pets_policy: nil)` | `pets_policy IS NOT NULL` | | `where.not(city: %w[Lyon Nice])` | `city NOT IN ('Lyon', 'Nice')` | | `where.not(city: "Lyon", furnished: true)` | `NOT (city = 'Lyon' AND furnished = TRUE)` | | `where.not("rent > 2000")` | `NOT (rent > 2000)` | ## Why NULL rows vanish SQL compares with **three-valued logic**: a comparison is true, false or **unknown**, and any comparison with `NULL` (other than `IS NULL` / `IS NOT NULL`) is unknown. A WHERE clause keeps a row only when the whole condition is **true**. So for an apartment whose `pets_policy` is `NULL`: 1. `pets_policy = 'none'` is unknown, so `where(pets_policy: "none")` skips it, as expected. 2. `pets_policy != 'none'` is also unknown, so `where.not(pets_policy: "none")` skips it too. The row matches neither the filter nor its negation. The Rails API documentation calls this out: a non-nil condition on a nullable column in `where.not` does not return records whose column is nil. ## Ways to include the NULL rows - **Add them explicitly**: `Apartment.where.not(pets_policy: "none").or(Apartment.where(pets_policy: nil))` gives `pets_policy != 'none' OR pets_policy IS NULL`. - **Fix the data model**: a `NOT NULL` constraint with a default such as `"ask"` removes the third state; this is usually the right answer for a column the app filters on. - **Decide deliberately** when you want them excluded: `where.not(pets_policy: ["none", nil])` produces `NOT (pets_policy = 'none' OR pets_policy IS NULL)`, which documents the intent. ## Several keys: NAND, not NOR With more than one key, `where.not` negates the **whole conjunction**. `Apartment.where.not(city: "Lyon", furnished: true)` keeps furnished flats outside Lyon and unfurnished flats in Lyon; it drops only furnished flats in Lyon. Rails 6.1 changed this from the older NOR behaviour, so code and answers written for Rails 6.0 or earlier read differently. To exclude both conditions separately, chain two calls: `where.not(city: "Lyon").where.not(furnished: true)`. ## NOT IN and a NULL in the list `where.not` with a relation becomes `NOT IN (subquery)`: ```ruby Apartment.where.not(id: Photo.select(:apartment_id)) # WHERE apartments.id NOT IN (SELECT photos.apartment_id FROM photos) ``` If any `photos.apartment_id` is `NULL`, then `id NOT IN (..., NULL)` is unknown for **every** row, and the query returns nothing. Two safer shapes are `where.missing(:photos)` (a LEFT OUTER JOIN with `IS NULL`) or adding `where.not(apartment_id: nil)` inside the subquery. ## excluding: negating by record `excluding` (alias `without`) is the record-level shorthand for `where.not(id: ...)`: - `Apartment.where(city: "Lyon").excluding(current_apartment)` gives `id != 42`, useful for "similar listings". - Passing several records or a relation gives `id NOT IN (...)`. - Passing a record of a different model raises `ArgumentError`. ## Strings and ranges behave the same way The NULL rule is not specific to hash conditions: - `where.not("rent > 2000")` becomes `NOT (rent > 2000)`; an apartment with a NULL `rent` makes the inner comparison unknown, `NOT unknown` is still unknown, and the row is dropped. - `where.not(rent: 900..1800)` negates the range predicate, and NULL rents again fall out of both the filter and its negation. - `where.not(pets_policy: nil)` is the one form that is NULL-aware by design: it writes `IS NOT NULL`, which is always true or false. A quick way to confirm what a negation will do is `relation.to_sql` in the console, followed by asking how each nullable column in the printed predicate behaves for a NULL row. ## Checklist - Ask "is this column nullable?" before every `where.not`. - Use a separate `where.not` per key when you mean "neither". - Prefer `where.missing` over `NOT IN (subquery)` on nullable foreign keys.
- How do you exclude both Lyon apartments and furnished apartments, rather than only furnished ones in Lyon?Chain two negations: `Apartment.where.not(city: "Lyon").where.not(furnished: true)`, which gives `city != 'Lyon' AND furnished != TRUE`. A single `where.not` with both keys negates the conjunction as a whole (NAND), so it keeps furnished flats outside Lyon. Remember both columns' NULLs still drop out.
- Why can Apartment.where.not(id: Photo.select(:apartment_id)) return no rows at all?It compiles to `id NOT IN (SELECT apartment_id FROM photos)`. If any photo has a NULL `apartment_id`, the NOT IN is unknown for every apartment, so nothing passes. Use `Apartment.where.missing(:photos)` or filter NULLs out of the subquery.
- What does excluding do, and when would you use it?`excluding(record_or_records)`, aliased `without`, adds `id != ?` or `id NOT IN (...)` for the records you pass, and raises `ArgumentError` for records of another model. It reads well for "other listings in this building": `building.apartments.excluding(@apartment)`.
- where.not(pets_policy: "none") also returns rows where pets_policy is NULL
- where.not with two keys excludes rows matching either key
- Rails rewrites != into IS DISTINCT FROM to handle NULLs automatically
- NOT IN with a subquery is always equivalent to where.missing
- excluding accepts records of any model and ignores the rest
Assumes Rails 8.1; where.not with several hash keys has generated NAND (NOT (a AND b)) since Rails 6.1, NOR before that.