skip to content

Filtering Conditions

where accepts hashes, ranges, arrays and bound placeholders, and combines with where.not, or and where.missing. Interviewers check that you filter without interpolation and predict NULL cases.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Active Record, what SQL does where generate when a hash condition's value is nil, an array, or a Ruby range?

level: juniorimportance: must knowfreq 72%

answer

  1. the value's class picks the operator
  2. nil never becomes = NULL
  3. arrays turn into IN lists
  4. endless range is one-sided
  5. empty array short-circuits the query

basics

~20 s

The value's type picks the operator: a scalar gives =, nil gives IS NULL, an array gives IN (...), and a range gives BETWEEN, or >=, < and <= comparisons for exclusive and open-ended ranges. Keys are ANDed together.

solid answer

~40 s

Active Record's predicate builder looks at each value's class. `Apartment.where(city: "Lyon")` gives `city = 'Lyon'`, `where(landlord_id: nil)` gives `landlord_id IS NULL` (never `= NULL`), `where(bedrooms: [2, 3])` gives `bedrooms IN (2, 3)`, and `where(rent: 900..1800)` gives `rent BETWEEN 900 AND 1800`. An endless range `900..` becomes `rent >= 900`, a beginless `..1800` becomes `rent <= 1800`, and an exclusive `900...1800` becomes `rent >= 900 AND rent < 1800`. An array holding `nil` adds `OR bedrooms IS NULL`, and an empty array becomes `1=0`, so no rows come back. Several keys are joined with `AND`, and the adapter binds and quotes every value, which is why the hash form is the default choice for equality and range filters.

code

ruby · 14 lines
ruby
Apartment.where(city: "Lyon", rent: 900..1800)
# WHERE city = 'Lyon' AND rent BETWEEN 900 AND 1800

Apartment.where(rent: 900...1800)
# WHERE rent >= 900 AND rent < 1800

Apartment.where(rent: ..1200)
# WHERE rent <= 1200

Apartment.where(bedrooms: [2, 3, nil])
# WHERE (bedrooms IN (2, 3) OR bedrooms IS NULL)

Apartment.where(bedrooms: []).to_a
# => [] and no SQL is sent (the predicate is 1=0)

go deeper

for a junior

Know the four shapes cold: scalar is =, nil is IS NULL, array is IN, range is BETWEEN. Be able to write a rent-range filter as where(rent: min..max).

for a middle

Explain the edges: exclusive and endless ranges, an array containing nil adding OR IS NULL, and an empty array becoming 1=0 with no query sent.

for a senior

Use these rules to keep optional filters correct: skip a where for an empty selection, choose exclusive ranges for time windows, and keep NULL semantics explicit in search code.

for a principal

Push teams toward hash conditions as the default because the builder owns quoting, casting and NULL handling, and keep string SQL to the few operators hashes cannot express.

## The rule: the value's type picks the operator `where` with a **hash condition** treats each key as a column (or attribute alias) and each value as the thing to match. Active Record's **predicate builder** dispatches on the value's class, so you never write the operator yourself. For a rental-listing site with an `Apartment` model: | Value | Example | SQL predicate | |---|---|---| | scalar | `where(city: "Lyon")` | `city = 'Lyon'` | | `nil` | `where(landlord_id: nil)` | `landlord_id IS NULL` | | array | `where(bedrooms: [2, 3])` | `bedrooms IN (2, 3)` | | one-element array | `where(bedrooms: [2])` | `bedrooms = 2` | | inclusive range | `where(rent: 900..1800)` | `rent BETWEEN 900 AND 1800` | | exclusive range | `where(rent: 900...1800)` | `rent >= 900 AND rent < 1800` | | endless range | `where(rent: 900..)` | `rent >= 900` | | beginless range | `where(rent: ..1800)` | `rent <= 1800` | | relation | `where(landlord_id: Landlord.where(verified: true))` | `landlord_id IN (SELECT landlords.id ...)` | Several keys in one hash, or several chained `where` calls, are joined with **AND**. ## Ranges Ruby ranges map cleanly onto price, date and size filters: - **Inclusive** `a..b` becomes `BETWEEN a AND b`, which includes both ends. - **Exclusive** `a...b` cannot use `BETWEEN`, so Arel writes `>= a AND < b`. This is the safe shape for time windows such as `Time.current.beginning_of_month...Time.current.next_month.beginning_of_month`, where you do not want the next month's first instant. - **Endless** `a..` and **beginless** `..b` (or `...b`) become one-sided comparisons, which is how a form with only a minimum or only a maximum rent maps onto one call. - A range whose two ends are equal collapses to plain `=`. ## Arrays, nil and the empty array Arrays are where the NULL surprises live: 1. `nil` is never compared with `=`. SQL's `col = NULL` is never true, so the builder writes `IS NULL`. 2. An array that **contains** `nil` is split: `where(bedrooms: [2, 3, nil])` becomes `bedrooms IN (2, 3) OR bedrooms IS NULL`. You get the NULL rows only because Rails added that branch. 3. An **empty array** becomes the always-false predicate `1=0`. When that predicate stands at the top level of the WHERE clause, Active Record recognises the contradiction and returns an empty result **without sending a query**. A search form that posts no checked boxes therefore returns nothing; if you meant "no filter", skip the `where` call instead. ## Records, associations and relations as values - On a `belongs_to`, `where(landlord: landlord)` is the same as `where(landlord_id: landlord.id)`; a polymorphic `belongs_to` adds the `_type` column too. - A **relation** as the value becomes a subquery: Rails selects the other model's primary key unless the relation already has a `select`. - A hash key can also be a **tuple** of columns with an array of tuples, which composite keys use: `where([:building_id, :unit] => [[4, "2B"], [4, "3A"]])`. ## How hash conditions compose Every `where` call adds to the same WHERE clause, so a search object can apply filters one at a time: - Chaining is **AND**: `Apartment.where(city: "Lyon").where(rent: ..1200)` equals one hash with both keys. - Repeating a key does **not** replace it: `where(rent: ..1200).where(rent: 900..)` keeps both predicates, which here happens to mean 900 to 1200, but `where(available: true).where(available: false)` matches nothing. Replacing a condition is what `rewhere` is for. - Keys may be **table-qualified strings**, such as `"apartments.rent"`, and attribute aliases declared with `alias_attribute` are translated to the real column. - Nothing runs until the relation is loaded, so building the chain costs no queries. ## Why prefer the hash form - **Quoting is automatic**: every value goes through the adapter as a bound value, so there is no string building. - **Type casting follows the attribute**: a string `"1800"` from params is cast for an integer `rent` column. - **Composition is safe**: hash conditions combine with `where.not`, `or` and `rewhere`, which can find and replace them by attribute name. The hash form cannot express everything. Comparisons such as `rent < deposit`, SQL functions, `LIKE` and database-specific operators need a string condition with placeholders, which is a separate topic. ## Traps worth naming - Writing `where("landlord_id = ?", nil)` puts `= NULL` into SQL and matches nothing; only the hash form rewrites `nil` to `IS NULL`. - A typo in a column name is not caught when `where` is called; the database raises `ActiveRecord::StatementInvalid` when the relation runs. - `where(nil)`, `where({})` and `where("")` are no-ops that return the relation unchanged, which is handy for optional filters but hides a missing value.

  • What does Apartment.where(bedrooms: []) return, and what does that mean for a checkbox filter?
    It returns an empty result. The predicate builder turns an empty array into `1=0`, and when that sits at the top of the WHERE clause Active Record skips the query entirely. If an empty selection should mean "no filter", guard the call (`scope = scope.where(bedrooms: ids) if ids.present?`) rather than passing the empty array through.
  • How would you filter apartments available from today onward without writing SQL?
    Use an endless range on the date column: `Apartment.where(available_from: Date.current..)`, which becomes `available_from >= '2026-10-06'`. A beginless range `..Date.current` gives the opposite, `<=`. Both are bound values, so no quoting or string building is involved.
  • What happens when the hash value is another relation, such as Landlord.where(verified: true)?
    Active Record embeds it as a subquery: `landlord_id IN (SELECT landlords.id FROM landlords WHERE verified = TRUE)`. If the inner relation has no `select`, Rails selects its primary key for you; with a `select`, that column is used. It is still one SQL statement, not two round trips.

  • where(landlord_id: nil) generates landlord_id = NULL, so it never matches
  • An empty array in a hash condition raises an error
  • where(rent: 900...1800) includes apartments that cost exactly 1800
  • A range value makes Active Record load every row and filter in Ruby
  • Hash conditions are interpolated into the SQL string unquoted
open as a page

In an Active Record where string, how do positional ? and :named placeholders bind their values, and how do they handle arrays?

level: middleimportance: must knowfreq 66%

basics

~20 s

Each ? takes the next extra argument and each :name takes the matching key of a trailing hash. Rails binds and quotes every value, expands an array into a comma list, and raises ActiveRecord::PreparedStatementInvalid when the counts do not match.

open as a page

In Active Record, why use exists? instead of present? to check whether any apartment matches a filter, and what SQL runs?

level: juniorimportance: should knowfreq 52%

basics

~20 s

exists? runs SELECT 1 AS one ... LIMIT 1 and returns true or false without building models, while present? loads every matching row into memory first. Use exists? when only the yes or no matters.

open as a page

In Active Record, how do where.missing and where.associated find apartments without photos or with photos, and what SQL do they run?

level: middleimportance: should knowfreq 38%

basics

~10 s

Apartment.where.missing(:photos) left-joins photos and keeps rows where photos.id IS NULL; Apartment.where.associated(:photos) inner-joins photos and keeps rows where photos.id IS NOT NULL. Both take association names and accept several at once.

open as a page

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?

level: middleimportance: should knowfreq 50%

basics

~20 s

where.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.

open as a page

In Active Record, how does Relation#or combine two relations, why does it raise 'must be structurally compatible', and where does its precedence surprise people?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Relation#or ORs the WHERE clauses of two relations of the same model that differ only in where or having; extra joins or limits on the argument raise ArgumentError. Conditions both sides share stay ANDed outside; the rest is grouped by AND before OR.

open as a page