In Active Record, how do count, size and length differ on a relation and on a has_many association, and what query does each run?
answer
- one ignores what is loaded
- one always loads the rows
- one checks loaded? first
- size counts unsaved built records
- includes plus count is still N+1
basics
~20 scount runs SELECT COUNT() even when the records are already loaded; length loads every record, then counts the Ruby array; size reuses loaded records when they exist and otherwise runs COUNT(), so size is the safe default when you do not know the load state.
solid answer
~40 sOn an Active Record relation or a `has_many` association of a saved record, `count` sends `SELECT COUNT(*)` to the database even when the records are already in memory. `length` loads the whole collection with `SELECT *` (if it is not loaded yet) and returns the array's length. `size` checks `loaded?`: if the records are in memory it counts them for free, otherwise it runs `COUNT(*)`. On an association, `size` also adds records built with `build` but not yet saved, while `count` only sees saved rows. So: `length` when you will iterate the records anyway, `count` when you need the database's current number, and `size` when you are not sure, which is the common case in views and partials.
code
ruby · 11 linesstore = Store.find(1)
store.sales.build(amount: 5) # unsaved
store.sales.count # COUNT(*): saved sales only, e.g. 12
store.sales.size # 13: the unsaved sale + COUNT(*)
stores = Store.includes(:sales)
stores.each do |s|
s.sales.size # preloaded array, no query
s.sales.count # COUNT(*) per store: N+1
endgo deeper
Recall the three behaviours: count always queries, length loads all rows, size picks based on whether the records are already loaded.
Explain how size branches on loaded?, why it includes unsaved built records on an association, and how count turns a preloaded collection back into an N+1.
Show that you read query logs for COUNT-then-SELECT pairs in views, choose load or length when rows are rendered, and use count only where freshness matters.
Discuss when per-request counts should give way to cached or denormalised counts, weighing staleness tolerance against the query load of large listings.
## Three names, three behaviours Active Record relations (`Sale.where(...)`) and `has_many` association proxies (`store.sales`) both answer `count`, `size` and `length`, but the three methods make different decisions about **whether to touch the database and how much to load**. Interviewers ask this because the wrong choice silently doubles queries or loads thousands of rows just to print a number. | Method | Not loaded yet | Already loaded | |---|---|---| | `count` | `SELECT COUNT(*)` | `SELECT COUNT(*)` again | | `length` | `SELECT "sales".*`, builds every record, then `Array#length` | `Array#length`, no query | | `size` | `SELECT COUNT(*)` | `Array#length`, no query | A relation is **loaded** once its records have been fetched, for example after `each`, `to_a`, `load` or `length`; `loaded?` reports it. ## count: always the database `count` is a calculation method, a shortcut for `calculate(:count, ...)`. It never looks at records in memory; the only shortcut is an association on a new, unsaved owner, covered below. That is useful when you need the current number (another process may have inserted rows) and wasteful when the same collection was just rendered. ```ruby store = Store.find(1) store.sales.count # SELECT COUNT(*) FROM "sales" WHERE "sales"."store_id" = 1 store.sales.length # SELECT "sales".* FROM "sales" WHERE "sales"."store_id" = 1 store.sales.size # no query: the association is loaded now store.sales.count # SELECT COUNT(*) ... again ``` ## length: always the records On a relation, `length` is delegated to the loaded records array, so it triggers a full load first. On an association it loads the target the same way. That is the right call only when the next line iterates over the same records; then the load is shared and no separate `COUNT` is needed. ## size: the adaptive one On a relation, `size` is literally: if `loaded?`, the length of the records, else `count(:all)`. On a `has_many` association it is richer: 1. If the association is loaded, it counts the in-memory target. 2. If the association is not loaded but records were added with `build`, it returns the number of **unsaved** built records **plus** a database count. 3. Otherwise it runs a `COUNT(*)` scoped to the owner. 4. If the association declares a counter cache, `size` reads the cached column instead of querying. Point 2 is a classic trap: after `store.sales.build(amount: 5)`, `store.sales.size` includes the new sale, but `store.sales.count` does not, because the row is not in the database yet. For a brand-new unsaved store, `count` returns `0` without querying at all. ## Relations versus associations The rules are the same in spirit but the association proxy knows more about its owner: | Situation | `count` | `size` | |---|---|---| | saved store, nothing built | `COUNT(*)` | `COUNT(*)` | | saved store, one sale built | saved rows only | saved rows + 1 | | new unsaved store | `0`, no query | in-memory built records | | association preloaded | `COUNT(*)` | array length, no query | A **new** owner has no primary key yet, so its association scope is turned into a `none` relation: `count` answers `0` without touching the database, and `size` counts whatever was built in memory. This is why a form that builds nested rows on a new record should display `size`, never `count`. ## Where this bites: views and eager loading - In a store index page that eager-loads with `Store.includes(:sales)`, each `store.sales.size` reads the preloaded array, but `store.sales.count` fires one `COUNT(*)` per store: an N+1 the `includes` was meant to prevent. - `@sales.any?` or `@sales.empty?` on an unloaded relation runs a cheap existence query, then the following `@sales.each` runs the full `SELECT`. When you know you will render the rows, calling `load` first lets both read from memory. - `size` on a **grouped** relation returns a Hash, because it falls through to `count(:all)`, which is a grouped count. ## How to choose - Rendering the records and also showing their number: `length`, or `load` first and then `size`. - Only the number, records not needed: `count` or `size`; both run `COUNT(*)` when nothing is loaded. - A shared partial that cannot know whether its caller loaded the collection: `size`. - A number that must reflect rows committed by other processes since the load: `count`.
- A partial shows `@sales.size` above an `@sales.each` loop and the log shows a COUNT and then a SELECT. How do you get one query?Load the relation before measuring it: `@sales = Sale.where(store_id: 7).load`, or call `length` instead of `size`. Once the relation is loaded, `size` returns the array's length and the loop reuses the same records, so only the `SELECT` runs.
- Why does `Sale.group(:store_id).size` return a Hash instead of an Integer?An unloaded relation's `size` delegates to `count(:all)`, and a counted relation that carries `group` performs a grouped calculation, which returns a Hash keyed by the grouped value, here each `store_id` with its row count.
- What do `empty?` and `any?` run on an unloaded association?On an unloaded collection they run an existence check (`SELECT 1 AS one ... LIMIT 1`) rather than a count, and once the collection is loaded they answer from memory. A declared counter cache lets `empty?` read the cached column instead.
Asking how many boxes of screws a store holds: count always phones the warehouse, even with the boxes already on your desk; length has every box shipped to your desk and counts them; size counts the desk if the boxes have arrived and phones only if they have not.
- count reuses already loaded records, so it never queries twice
- length is the cheap one because it runs COUNT(*)
- size always runs SELECT COUNT(*), even after the records are loaded
- store.sales.count includes sales built with build but not yet saved
- after includes(:sales), calling count on each store's sales runs no extra queries