skip to content

In Active Record, what SQL do count, count(:coupon_code), distinct.count(:store_id) and Store.joins(:sales).count run, and why do their numbers differ?

level: middleimportance: should knowfreq 45%

answer

  1. COUNT(*) versus COUNT(column)
  2. NULLs drop out of a column count
  3. distinct becomes COUNT(DISTINCT ...)
  4. a join counts joined rows
  5. LIMIT forces a subquery

basics

~10 s

count and count(:all) run COUNT(*); count(:column) runs COUNT(column) and skips NULLs; distinct.count(:column) runs COUNT(DISTINCT column); and a join counts joined rows, so Store.joins(:sales).count returns sales rows, not stores.

solid answer

~30 s

`Sale.count` (and `Sale.count(:all)`) runs `SELECT COUNT(*) FROM "sales"`: every row. `Sale.count(:coupon_code)` runs `COUNT("sales"."coupon_code")`, which SQL evaluates by skipping NULLs, so it answers how many sales used a coupon. `Sale.distinct.count(:store_id)` runs `COUNT(DISTINCT "sales"."store_id")`: how many stores sold something. `Store.joins(:sales).count` counts rows of the joined result, one per sale, so a store with 40 sales counts 40 times; `Store.joins(:sales).distinct.count` rewrites to `COUNT(DISTINCT "stores"."id")`. When the relation has a `limit` or `offset`, `count` wraps it in a subquery so the limit still applies.

code

ruby · 10 lines
ruby
Sale.count                       # SELECT COUNT(*) FROM "sales"
Sale.count(:coupon_code)         # SELECT COUNT("sales"."coupon_code") ...
Sale.distinct.count(:store_id)   # SELECT COUNT(DISTINCT "sales"."store_id") ...

Store.joins(:sales).count        # one row per sale: inflated
Store.joins(:sales).distinct.count
# SELECT COUNT(DISTINCT "stores"."id") FROM "stores" INNER JOIN "sales" ...

Sale.limit(10).count
# SELECT COUNT(*) FROM (SELECT 1 AS one FROM "sales" LIMIT 10) subquery_for_count

go deeper

for a junior

Recall that count with no argument is COUNT(*), a column argument skips NULLs, and distinct turns it into COUNT(DISTINCT ...).

for a middle

Explain why a join inflates count, how distinct rewrites it to count primary keys, and why a limit makes Rails wrap the count in a subquery.

for a senior

Show that you check the generated SQL behind every dashboard number, pick the counted table deliberately, and catch inflated counts before they reach a report.

for a principal

Discuss defining each business metric once, as a named relation or reporting query, so teams do not ship slightly different counts of the same thing.

## count is one method with several SQL shapes `count` on an Active Record relation is the calculation `calculate(:count, column_name)`. What it sends depends on the argument and on what the relation already carries. In a hardware chain's `sales` table (columns `store_id`, `amount`, `coupon_code`, `sold_on`) the variants answer different business questions: | Ruby | SQL aggregate | Answers | |---|---|---| | `Sale.count` | `COUNT(*)` | how many sales rows | | `Sale.count(:all)` | `COUNT(*)` | same; `:all` is an alias for `*` | | `Sale.count(:coupon_code)` | `COUNT("sales"."coupon_code")` | how many sales had a coupon | | `Sale.distinct.count(:store_id)` | `COUNT(DISTINCT "sales"."store_id")` | how many stores sold anything | | `Store.joins(:sales).count` | `COUNT(*)` over the join | how many (store, sale) pairs | ## Column counts and NULL `COUNT(column)` is standard SQL: it counts rows where that column is **not NULL**. So with 100 sales of which 30 have no coupon, `Sale.count` is 100 and `Sale.count(:coupon_code)` is 70. Candidates who think a column argument only "names" the count get these numbers wrong. A relation with a single `select` column counts that column the same way: `Sale.select(:coupon_code).count` also runs `COUNT("sales"."coupon_code")`. ## distinct Calling `distinct` on the relation marks the calculation as distinct: - `Sale.distinct.count(:store_id)` emits `COUNT(DISTINCT "sales"."store_id")`. The database removes duplicates; no ids are loaded into Ruby. - With no column and no `select`, a distinct count on a model counts its primary key: `Store.joins(:sales).distinct.count` becomes `SELECT COUNT(DISTINCT "stores"."id") FROM "stores" INNER JOIN "sales" ...`. - When the relation also has an `order`, Rails falls back to counting a `SELECT DISTINCT` subquery instead. ## Counting across a join `joins` produces one result row per matching pair. `Store.joins(:sales).count` therefore returns the number of sales that have a store, not the number of stores. The fix depends on the question: 1. "How many stores have at least one sale?" `Store.joins(:sales).distinct.count`, or `Sale.distinct.count(:store_id)`. 2. "How many sales per store?" a grouped count, `Sale.group(:store_id).count`. 3. "How many stores in total?" `Store.count`, no join. Using `size` instead does not help: on an unloaded relation `size` delegates to `count(:all)` and returns the same inflated number. ## limit, offset and the subquery A plain `SELECT COUNT(*) ... LIMIT 10` would apply the limit to the single aggregate row, not to the rows being counted. Active Record avoids that: when the relation has a `limit` or `offset`, `count` builds ```sql SELECT COUNT(*) FROM (SELECT 1 AS one FROM "sales" LIMIT 10) subquery_for_count ``` so `Sale.order(:sold_on).limit(10).count` returns at most 10, and the inner query drops the `ORDER BY` because it cannot change the number. `limit(0).count` returns `0` without a query. ## count(:all) and a custom select `count` with no argument looks at the relation's `select` list. With one selected column it counts that column (NULLs skipped); with several selected columns it would emit `COUNT("sales"."store_id", "sales"."amount")`, which most databases reject. `count(:all)` sidesteps this: it always counts rows with `COUNT(*)`, whatever the relation selects. That is why code that receives an arbitrary relation, such as a pagination helper or a shared partial, should call `count(:all)` rather than `count`. ## count with an eager-loading JOIN When a relation uses `includes` and a condition on the included table forces it to load with a `JOIN`, `count` cannot simply count the joined rows, because that would count sales instead of stores. Active Record therefore switches the count to the base model's primary key with `DISTINCT`: ```ruby Store.includes(:sales).where(sales: { status: "refunded" }).count # SELECT COUNT(DISTINCT "stores"."id") FROM "stores" # LEFT OUTER JOIN "sales" ON "sales"."store_id" = "stores"."id" # WHERE "sales"."status" = 'refunded' ``` A plain `joins` gets no such rewriting: the `DISTINCT` has to be asked for explicitly. ## Other details worth knowing - `count` returns an `Integer` and `0` for an empty set, never `nil`. - A block form exists, `Sale.count { |s| s.amount > 100 }`, but it loads every record and counts in Ruby; passing a column and a block together raises `ArgumentError`. Prefer `where(amount: 100..).count` style conditions. - A `group` on the relation turns any of these into a Hash of counts per group.

  • Why can `Store.joins(:sales).count` and `Store.joins(:sales).to_a.size` agree, yet both be wrong for 'stores with sales'?
    Both see the joined result: `count` counts joined rows in SQL, and `to_a` loads one `Store` object per joined row, duplicates included. Neither collapses a store with many sales into one. Add `distinct` so the count becomes `COUNT(DISTINCT stores.id)` and the load uses `SELECT DISTINCT`.
  • What does `Sale.count { |s| s.amount > 100 }` cost compared with a where-based count?
    The block form loads every sale and evaluates the condition in Ruby, so the cost grows with the table. `Sale.where("amount > ?", 100).count` sends one `COUNT(*)` with the condition in the `WHERE` clause and returns the same integer.

  • count(:coupon_code) counts every row, NULLs included
  • Sale.limit(10).count ignores the limit and counts the whole table
  • Store.joins(:sales).count returns the number of stores
  • distinct.count(:store_id) loads the ids and calls uniq in Ruby
  • switching joins(...).count to size removes the duplicate rows