Practice · Reading the Source · Card 2
Which line actually runs the SQL?
Five lines of User.where(...) chaining. Only one of them hits the database. Pick it.
The code
Reading top to bottom, which line is the moment the database wakes up?
def call
users = User.where(active: true) # line 1
users = users.where(role: "admin") # line 2
users = users.order(:created_at).limit(10) # line 3
Rails.logger.info "Found admins" # line 4
users.each { |u| send_email(u) } # line 5
end The question
Which of the five lines is the first to send SQL to the database?
Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.
✅ Answer breakdown
✗ A. Line 1 — User.where(active: true)
where returns an ActiveRecord::Relation. The Relation is a description of a query, not a query result. No SQL has run.
✗ B. Line 2 — chained .where(role: "admin")
Chaining another where just produces a new Relation with both conditions merged into its spec. Still no SQL.
✗ C. Line 3 — chained .order(:created_at).limit(10)
Same story. order and limit add to the Relation's spec and return a new Relation. No database call yet.
✓ D. Line 5 — users.each { ... }
.each is the first method here that needs the actual rows. That's when Rails finally runs the SQL, loads the results into memory, and yields each User to the block.
💡 The principle
A Relation is lazy. It collects spec (where, order, limit, includes, joins) without touching the database. It only runs SQL when something asks for the actual data: .each, .to_a, .first, .count, .pluck, .exists?, .find_each, or interpolation into a view (which calls .to_a).
Methods that return a new Relation (where, order, limit, joins, includes, select, group, having) do not run SQL. Knowing the split lets you compose queries safely over many lines without performance worry, and lets you call .to_sql to inspect what the SQL will look like before triggering it.
📚 Theory
For the full walkthrough, read Reading the Source · Card 3 — How User.where(...) becomes SQL.