In Active Record, what do sum, average, minimum and maximum return on a relation, and what comes back when no rows match?
answer
- one SQL aggregate, no records built
- empty SUM is turned into 0
- AVG of integer or decimal: BigDecimal
- MIN/MAX keep the column's type
- a block switches to Ruby
basics
~20 sCalled with a column, each runs one SQL aggregate and returns a single cast value: sum returns 0 when nothing matches, average returns a BigDecimal for integer and decimal columns, and average, minimum and maximum return nil on an empty set.
solid answer
~40 s`Sale.where(store_id: 7).sum(:amount)` runs `SELECT SUM("sales"."amount") FROM "sales" WHERE ...` and never instantiates a `Sale`. The result is cast through the column's type, so a decimal column sums to a `BigDecimal`, and when no row matches Rails turns SQL's NULL into `0`. `average` returns a `BigDecimal` for integer and decimal columns (a float column stays `Float`) and `nil` when nothing matches; `minimum` and `maximum` return the column's own type, such as a `Date` for `sold_on`, or `nil`. All four are shortcuts for `calculate(:sum, :amount)` and its siblings. Passing a block to `sum` is a different method in practice: it loads every record and adds the block's values in Ruby.
code
ruby · 6 linesSale.where(store_id: 7).sum(:amount) # => 18250.75 (BigDecimal)
Sale.where(store_id: 99).sum(:amount) # => 0 (no rows)
Sale.average(:quantity) # => 0.42e1 (BigDecimal)
Sale.where(store_id: 99).average(:amount) # => nil
Sale.where(store_id: 7).minimum(:sold_on) # => Thu, 01 Jan 2026 (Date)
Sale.calculate(:maximum, :amount) # same as Sale.maximum(:amount)go deeper
Recall that these methods run one aggregate query and return a value, with 0 from an empty sum and nil from an empty average, minimum or maximum.
Explain the casting: sum and min/max follow the column type, average gives BigDecimal for integer and decimal columns, and a block makes sum load every record.
Show you guard nil averages in reports, keep arithmetic in SQL expressions for large tables, and decide deliberately how BigDecimal totals are serialised to API clients.
Weigh computing dashboard aggregates on each request against precomputed rollups, considering table growth, freshness requirements and how much read load the primary database can absorb.
## What the four methods are In Active Record, `sum`, `average`, `minimum` and `maximum` are **calculation methods** defined on every relation (and therefore on every model class and every `has_many` association). Each one asks the database for a single aggregate value instead of loading rows into Ruby objects. They are thin wrappers around one general method, `calculate(operation, column_name)`: - `sum(:amount)` is `calculate(:sum, :amount)` and emits `SUM(...)` - `average(:quantity)` is `calculate(:average, :quantity)` and emits `AVG(...)` - `minimum(:sold_on)` is `calculate(:minimum, :sold_on)` and emits `MIN(...)` - `maximum(:amount)` is `calculate(:maximum, :amount)` and emits `MAX(...)` The relation's conditions become the `WHERE` clause, so `Sale.where(store_id: 7, sold_on: Date.new(2026, 9, 1)..).sum(:amount)` totals one store's September-onward sales in a single statement. No `Sale` object is built, which is why these methods are the right tool for a dashboard figure. ## The SQL they run ```ruby Sale.where(store_id: 7).sum(:amount) # SELECT SUM("sales"."amount") FROM "sales" WHERE "sales"."store_id" = 7 Sale.average(:quantity) # SELECT AVG("sales"."quantity") FROM "sales" Sale.where(store_id: 7).maximum(:sold_on) # SELECT MAX("sales"."sold_on") FROM "sales" WHERE "sales"."store_id" = 7 ``` For a simple (ungrouped) calculation Active Record also drops any `ORDER BY` the relation carries, because an order is meaningless for one aggregate row. The column may also be an SQL expression, as in `Sale.sum("quantity * unit_price")`; an expression has no attribute type, so its value is whatever the database adapter hands back. ## Return types The aggregate comes back as a raw database value and is then **cast** in Ruby: | Method | Rows match | No row matches | |---|---|---| | `count` | `Integer` | `0` | | `sum` | the column's type (`Integer`, `BigDecimal`, ...) | `0`, cast to the column's type | | `average` | `BigDecimal` for integer and decimal columns, the column's type otherwise | `nil` | | `minimum` / `maximum` | the column's type (`Date`, `Time`, `BigDecimal`, ...) | `nil` | Two details deserve emphasis: 1. **`sum` never returns `nil`.** SQL's `SUM` over zero rows is NULL, but Rails substitutes `0` before casting, so a store with no sales shows a total of `0` without a guard. 2. **`average` is not a `Float` for integer or decimal columns.** Active Record converts it with `to_d`, so `Sale.average(:quantity)` returns something like `0.42e1`, a `BigDecimal`. The method's own API comment still says AVG is cast to Float; the source in Rails 8.1 casts integer and decimal averages to `BigDecimal`, and the source is what runs. ## Empty results and nil guards Because `average`, `minimum` and `maximum` return `nil` when nothing matches, code such as `Sale.where(store_id: 99).average(:amount).round(2)` raises `NoMethodError` for a new store with no sales. Typical defences are `&.round(2)` or an explicit fallback such as `|| 0`. The same applies to dates: `maximum(:sold_on)` is `nil` until the first sale exists. A relation built with `none` short-circuits entirely: `Sale.none.sum(:amount)` returns `0` and `Sale.none.maximum(:amount)` returns `nil` without sending any SQL. ## Blocks change the meaning `sum` and `count` also accept a block, and then they stop being SQL aggregates: - `Sale.where(store_id: 7).sum { |sale| sale.amount * sale.tax_rate }` loads **every** matching row, builds a `Sale` for each, and adds the block results in Ruby (the optional argument becomes the starting value, so `sum(1000) { ... }` starts from 1000). - That is acceptable for a handful of records already loaded, and a memory and time problem for a year of sales across a hardware chain. When the arithmetic can be expressed in SQL, pass the expression as the column instead, for example `sum("amount * tax_rate")`, so the database does the work. ## On associations and scopes Because calculation methods live on relations, they compose with everything that produces one: - `store.sales.sum(:amount)` adds the association's foreign-key condition, `WHERE "sales"."store_id" = 7`, and still runs one aggregate query. - A named scope chains in front of the calculation: `Sale.where(status: "paid").maximum(:amount)` or `store.sales.where(sold_on: Date.current.all_month).sum(:amount)`. - The calculation is the **end of the chain**. It returns a number, a date or `nil`, not a relation, so nothing can be chained after it and it runs immediately rather than lazily. For money, keep the `BigDecimal` that a decimal column produces. Converting individual amounts to `Float` before adding them, or summing floats in Ruby, reintroduces binary rounding errors that the decimal column exists to avoid; convert only at the presentation edge, if at all. ## Interview takeaways - Calculation methods return **values**, not relations; nothing can be chained after them. - Know the empty-set behaviour: `0` for `sum` and `count`, `nil` for the other three. - Know that `average` on integer or decimal columns gives a `BigDecimal`, which serialises to JSON as a **string**. - Prefer a column or SQL expression over a block whenever the data set is large.
- Why does a dashboard's JSON show the average sale quantity as "4.2" in quotes?`average` on an integer or decimal column returns a `BigDecimal`, and Active Support's `BigDecimal#as_json` returns a string to avoid float precision loss on the client. If the contract wants a JSON number, convert explicitly with `to_f` (accepting the rounding) or keep the string and document it.
- What is the difference between `Sale.sum(:amount)` and `Sale.sum(&:amount)`?The first runs one `SELECT SUM(...)` in the database and returns a value. The second passes a block, so Active Record loads every `Sale` row, instantiates each record and adds `amount` in Ruby. Same answer, very different cost on a large table.
- sum returns nil when no rows match, so every total needs a nil guard
- average always returns a Float, whatever the column type
- average returns 0 for an empty table, like sum does
- minimum and maximum load the records and compare them in Ruby
- sum with a block still runs a single SQL SUM