In Active Record, why use exists? instead of present? to check whether any apartment matches a filter, and what SQL runs?
answer
- one row is enough
- SELECT 1 AS one ... LIMIT 1
- present? loads every record
- any? and empty? reuse loaded records
- a record argument raises ArgumentError
basics
~20 sexists? 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.
solid answer
~50 s`Apartment.where(city: "Lyon", rent: ..900).exists?` normally drops the relation's select, order and distinct, runs `SELECT 1 AS one FROM apartments WHERE ... LIMIT 1`, and returns a boolean. `present?` on a relation calls `blank?`, which loads every matching row and instantiates an object for each, just to answer yes or no. `any?` and `empty?` sit in between: on an unloaded relation they call `exists?`, and on a loaded one they check the array in memory, while `exists?` ignores loaded records and runs its query. So use `exists?` when you only need the answer, and load once and use `any?` when you will render the records anyway. `exists?` also takes conditions directly, such as `exists?(city: "Lyon")`, an id, or `["rent < ?", 900]`; passing a record raises `ArgumentError`, and a bare string is treated as a primary key.
code
ruby · 14 lines# yes/no only: one tiny query, no objects built
if SavedSearch.find(params[:id]).apartments.exists?
notify_subscriber
end
Apartment.exists?(landlord_id: landlord.id, available: true)
# SELECT 1 AS one FROM apartments WHERE ... LIMIT 1
# rendering anyway: load once, then reuse
@apartments = Apartment.where(city: "Lyon").load
@apartments.any? # no extra query
Apartment.exists?(@apartment)
# => ArgumentError: You are passing an instance of ActiveRecord::Base to `exists?`.go deeper
Use exists? for yes/no checks and remember that present? on a relation loads every record first.
Explain the SELECT 1 AS one LIMIT 1 query, how any? and empty? switch between exists? and the loaded array, and the argument forms exists? accepts.
Count queries per view: load once when records are rendered, use exists? in policies and guards, and catch record or string arguments in review.
Make query count per request a review habit, so existence checks stay one-row questions as listing pages grow.
## The problem exists? solves A common question in a listing site is "is there anything to show?": does a saved search have any matching apartment, does a landlord have any active listing, should the empty-state banner appear? Loading rows to answer a yes/no question wastes memory and time. `exists?` asks the database the smallest possible question. ## What exists? runs ```ruby Apartment.where(city: "Lyon", rent: ..900).exists? # SELECT 1 AS one FROM apartments # WHERE city = 'Lyon' AND rent <= 900 LIMIT 1 ``` Before running, Active Record: - removes the relation's `select`, `distinct` and `order`, since they do not change whether a row exists (when `distinct` is combined with `offset`, it keeps them and only drops the order), - selects the constant `1 AS one` and adds `LIMIT 1`, - returns `false` **without querying** for `Apartment.none`, for `limit(0)`, and when the WHERE clause is a known contradiction such as `where(id: [])`. The database can stop at the first matching index entry, so with a suitable index this is about as cheap as a query gets. ## Arguments exists? accepts | Call | Meaning | |---|---| | `exists?` | does the relation have any row | | `exists?(42)` or `exists?("42")` | is there a row with this primary key | | `exists?(city: "Lyon")` | hash conditions, as in `where` | | `exists?(["rent < ?", 900])` | array conditions with placeholders | | `exists?(false)` | always `false` | Two traps: 1. **A bare string is treated as a primary key.** `exists?("rent < 900")` compares the id with that text instead of running a condition. 2. **A record raises.** `exists?(apartment)` raises `ArgumentError` asking you to pass the id; use `exists?(apartment.id)`. ## exists? versus the other predicates | Method on a relation | Unloaded relation | Loaded relation | |---|---|---| | `exists?` | `SELECT 1 ... LIMIT 1` | still queries the database | | `any?` / `empty?` / `none?` | delegates to `exists?` | checks the loaded array | | `present?` / `blank?` | loads all records, then checks | checks the loaded array | This leads to two rules of thumb: - **Only need the answer**: call `exists?` (or `any?`) on an unloaded relation. One tiny query, no objects. - **Will render the records anyway**: load once (iterate, or call `load`) and then use `any?` or `empty?`, which reuse the loaded array. Calling `exists?` first and then iterating costs two queries. `present?` is the one to avoid on unloaded relations: it reads naturally in a view (`if @apartments.present?`) but quietly loads everything just to discard it, unless the same view iterates over the same relation right after, in which case the records are reused. ## Patterns to replace in code review | Seen in code | Problem | Replace with | |---|---|---| | `Apartment.where(...).present?` used only as a condition | loads every row | `Apartment.where(...).exists?` | | `Apartment.where(...).to_a.any?` | loads every row, then checks | `Apartment.where(...).any?` | | `Apartment.where(...).first.present?` | builds one full model and adds an ORDER BY | `Apartment.where(...).exists?` | | `exists?` followed by iterating the same relation | two queries | `load`, then `any?` | `exists?` is also the natural fit outside views: in a policy (`landlord.apartments.exists?(id: record.id)`), in a custom validation that must check for a conflicting listing, or in a job that decides whether there is work to do. ## A note on the query cache Inside a controller action, Rails' query cache can serve a repeated identical `exists?` from memory, but it is cleared by any write. Do not design around it; design around how many distinct questions you ask. ## Checklist - `exists?` for yes/no on unloaded relations and in policy or validation code. - Never pass a record or a raw SQL string to `exists?`. - In views, decide whether the records are rendered; if so, load once and use `any?`.
- A view calls @apartments.any? and then iterates @apartments. How many queries run, and how would you reduce them?If `@apartments` is unloaded, `any?` runs a `SELECT 1 ... LIMIT 1` and the iteration then loads the rows: two queries. Call `load` first (or iterate before checking), and `any?` reuses the loaded array, leaving one query.
- What does Apartment.exists?("rent < 900") actually check?It treats the string as a primary-key value, so it looks for an apartment whose id equals that text; it does not evaluate the condition. Use `Apartment.exists?(["rent < ?", 900])` or `Apartment.where(rent: ...900).exists?`.
- present? on a relation runs a cheap SELECT 1 query
- exists? reuses the records when the relation is already loaded
- exists?("rent < 900") evaluates the string as a condition
- You can pass a record to exists? to check it is still in the table
- exists? keeps the relation's order and select clauses