In Active Record, how do first, last, take and sole differ in the SQL they run and in what they return when nothing matches?
answer
- which ones add an ORDER BY
- first orders by primary key
- take adds only LIMIT 1
- sole fetches two rows
- bang versions raise RecordNotFound
basics
~20 sOn an unordered relation, first sorts by the primary key (or implicit_order_column) ascending with LIMIT 1, last reverses that order, and take adds only LIMIT 1. All three return nil when nothing matches; sole raises unless exactly one row matches.
solid answer
~40 sOn a relation with no order, `Restaurant.where(city: "Lyon").first` runs `ORDER BY restaurants.id ASC LIMIT 1`, `last` runs `ORDER BY restaurants.id DESC LIMIT 1`, and `take` runs a bare `LIMIT 1`, so the database returns whichever row it finds first. With an explicit `order`, `first` keeps it and `last` reverses it. All three return `nil` on no match, and `first!`, `last!` and `take!` raise `ActiveRecord::RecordNotFound` instead. `sole` runs `LIMIT 2` and returns the record only when exactly one exists, raising `RecordNotFound` for none and `ActiveRecord::SoleRecordExceeded` for more. Pass a number (`first(3)`) and you get an array. Use `take` when any match will do and you want no sort, `first` or `last` when the position matters, and `sole` when duplicates would be a bug.
code
ruby · 11 linesRestaurant.where(city: "Lyon").first # ORDER BY id ASC LIMIT 1
Restaurant.where(city: "Lyon").take # LIMIT 1
Restaurant.order(rating: :desc).last # ORDER BY rating ASC LIMIT 1
Restaurant.where(slug: "chez-lou").sole
# SELECT ... WHERE slug = 'chez-lou' LIMIT 2
# 0 rows => ActiveRecord::RecordNotFound
# 2 rows => ActiveRecord::SoleRecordExceeded
Restaurant.where(city: "Nowhere").first # => nil
Restaurant.where(city: "Nowhere").first! # => ActiveRecord::RecordNotFoundgo deeper
Remember that first and last sort by primary key when no order is given, take does not sort, and only the bang versions raise when nothing is found.
Describe the SQL of each finder, how last reverses an explicit order, sole's LIMIT 2 and its two exceptions, and when last falls back to Ruby.
Pick finders by intent: explicit order for positional reads, take to avoid sorts, sole where duplicates mean corruption, and watch last on offset relations.
Encourage code that states its expectation, sole for uniqueness and explicit order for position, so data bugs fail loudly instead of returning a plausible row.
## The four finders at a glance | Call | SQL added | No match | Several matches | |---|---|---|---| | `first` | `ORDER BY <order columns> ASC LIMIT 1` (unless already ordered) | `nil` | the first in that order | | `last` | the same order reversed, `LIMIT 1` | `nil` | the last in that order | | `take` | `LIMIT 1`, no order | `nil` | any one, database's choice | | `sole` | `LIMIT 2`, no order | raises `ActiveRecord::RecordNotFound` | raises `ActiveRecord::SoleRecordExceeded` | `first!`, `last!` and `take!` are the raising versions: they return the record or raise `ActiveRecord::RecordNotFound`. ## first and last: an implied order `first` and `last` are **order-dependent finders**. When the relation has no `order`, Active Record supplies one from the model's **order columns**: 1. `implicit_order_column`, if the model sets it, 2. followed by the **primary key** (or the composite `query_constraints`), which acts as a tiebreaker. So for a restaurants table with an integer `id`: ```ruby Restaurant.where(city: "Lyon").first # SELECT ... WHERE city = 'Lyon' ORDER BY restaurants.id ASC LIMIT 1 Restaurant.where(city: "Lyon").last # SELECT ... WHERE city = 'Lyon' ORDER BY restaurants.id DESC LIMIT 1 Restaurant.order(rating: :desc).first # SELECT ... ORDER BY rating DESC LIMIT 1 (no id added) ``` Details worth knowing: - `last` with an explicit order **reverses** it (`rating ASC`). Orders Rails cannot reverse, such as a string containing `NULLS LAST`, raise `ActiveRecord::IrreversibleOrderError`. - `first(3)` and `last(3)` return arrays; `last(3)` comes back in ascending order, not newest first. - On a relation that is **already loaded**, or that already has a `limit` or `offset`, `last` takes the final element of the loaded records in Ruby instead of reversing the SQL, which can mean loading the whole result. - `second`, `third`, `fourth`, `fifth` and `forty_two` use the same order with an `OFFSET`. ## take: no order at all `take` adds only `LIMIT 1`. It is the right call when **any** matching row will do, for example "is there a restaurant with this slug, and give it to me". Without an order the database may return a different row from one run to the next, so never use `take` where position matters. ## sole: exactly one `sole` encodes an expectation: the filter should match **one** row. 1. It fetches up to two rows with `LIMIT 2`. 2. Zero rows raise `RecordNotFound`; two rows raise `SoleRecordExceeded`. 3. One row is returned. `find_sole_by(slug: "chez-lou")` is the same check written as a lookup. Use it where a duplicate would mean corrupt data, for instance a natural key that lacks a unique index yet. ## Memoised results and related lookups - `first` and `take` remember their answer on the relation object: calling `rel.first` twice runs one query. `reset` (or `reload`) clears it. - `find_by` is implemented as `where(...).take`, so it adds no `ORDER BY`; if several rows match, which one you get is up to the database. - `first` on a relation that is **already loaded** reads `records[0]` without a query, which is cheap but reflects the order the relation was loaded in. - A console habit of `Restaurant.last` to see "the newest record" only works when the primary key follows insertion order. ## Choosing - **Position matters** (newest, cheapest, best rated): give an explicit `order`, then `first`. - **Any row will do**: `take`, which avoids a sort. - **Exactly one must exist**: `sole`, so the bug surfaces instead of hiding. - **A missing row is an error**: the bang version, so the controller's 404 handling applies. ## A Rails 8.1 note On a model that has **no** order columns at all (no primary key, no `implicit_order_column`, no `query_constraints`), an unordered `first` cannot pick a default sort. Rails 8.1 deprecates that silent case, and a new app's `load_defaults 8.1` makes it raise `ActiveRecord::MissingRequiredOrderError`. Ordinary tables with an `id` are unaffected.
- Why can Restaurant.order(rating: :desc).offset(20).last be expensive?With an `offset` (or `limit`) already on the relation, `last` cannot simply reverse the order, so it loads the remaining rows and takes the final one in Ruby. On a large table that means instantiating every restaurant after the 20th. Reverse the order yourself and use `first` instead.
- When would you choose sole over first in a controller?When more than one match would be a data bug, for example a slug that should be unique but has no index yet. `sole` raises `ActiveRecord::SoleRecordExceeded` instead of silently showing one of the duplicates, so the problem surfaces in error tracking rather than as the wrong page.
- take orders by the primary key just like first
- first raises RecordNotFound when no restaurant matches
- sole returns the first record when two match
- last(3) returns the newest record first
- first ignores an explicit order and always sorts by id
Assumes Rails 8.1; with load_defaults 8.1 an unordered first or last on a model with no order column (primary key, implicit_order_column or query_constraints) raises MissingRequiredOrderError instead of returning an arbitrary row.