In Active Record, what does Sale.group(:store_id).sum(:amount) return, and how do having and regroup change a grouped calculation?
answer
- a Hash, not an Array
- keys are the grouped values
- several columns give Array keys
- having filters groups, where filters rows
- regroup replaces, group appends
basics
~20 sA grouped calculation returns a Hash keyed by the grouped value, here each store_id mapped to its total; having filters whole groups by an aggregate after grouping, and regroup replaces the existing GROUP BY instead of appending to it.
solid answer
~30 s`Sale.group(:store_id).sum(:amount)` runs one `SELECT SUM("sales"."amount") ..., "sales"."store_id" ... GROUP BY "sales"."store_id"` and returns a Hash like `{1 => 18250.75, 2 => 9120.0}`. Grouping by several columns gives Array keys, and grouping by a `belongs_to` name such as `:store` gives the `Store` records themselves as keys, at the cost of one extra query. `where` filters rows before grouping; `having("SUM(sales.amount) > ?", 50_000)` filters groups after aggregation. `group` calls accumulate, so a second `group` adds a column; `regroup` (Rails 7.1+) swaps the whole `GROUP BY`, as shorthand for `unscope(:group).group(...)`.
code
ruby · 12 linesSale.group(:store_id).sum(:amount)
# => {1 => 18250.75, 2 => 9120.0} (BigDecimal values)
Sale.group(:store_id, :status).count
# => {[1, "paid"] => 410, [1, "refunded"] => 12}
Sale.group(:store).sum(:amount)
# => {#<Store id: 1 ...> => 18250.75, ...} (plus SELECT on stores)
by_store = Sale.group(:store_id)
by_store.group(:status).count # GROUP BY store_id, status
by_store.regroup(:status).count # GROUP BY statusgo deeper
Recall that group plus a calculation returns a Hash keyed by the grouped value, and that having filters groups by an aggregate.
Explain where versus having in execution order, the Array keys from multi-column groups, and why grouping by a belongs_to name costs a second query.
Show that you build report relations that compose safely: regroup instead of stacking group, bound having thresholds, and explicit ordering for dashboard output.
Decide when grouped aggregates computed on request should move to summary tables or a reporting replica as the sales history grows.
## Grouped calculations return a Hash Any calculation method (`count`, `sum`, `average`, `minimum`, `maximum`, `calculate`) on a relation that has a `group` clause becomes a **grouped calculation**. Active Record adds the grouped column to the `SELECT`, runs one query, and builds a Hash: each key is a grouped value, each value is that group's aggregate, cast the same way an ungrouped calculation would be. ```ruby Sale.where(sold_on: Date.new(2026, 1, 1)..).group(:store_id).sum(:amount) # SELECT SUM("sales"."amount") AS sum_amount, "sales"."store_id" AS sales_store_id # FROM "sales" WHERE "sales"."sold_on" >= '2026-01-01' # GROUP BY "sales"."store_id" # => {1 => 18250.75, 2 => 9120.0, 5 => 40310.5} ``` A store with no sales is simply absent from the Hash; a grouped calculation over no rows returns `{}`. The Hash follows the order the database returned, so add an `order` when the dashboard needs one. ## The shape of the keys | Group call | Key in the result | |---|---| | `group(:store_id)` | the store id, e.g. `1` | | `group(:store_id, :status)` | an Array, e.g. `[1, "refunded"]` | | `group(:store)` (a `belongs_to`) | the `Store` record, loaded by a second query | | `group("DATE_TRUNC('month', sales.sold_on)")` | the month value the database returns (PostgreSQL function) | The `belongs_to` form is convenient in views (`totals.each { |store, total| ... }`) but costs that extra `SELECT` on `stores`. A hardware chain's "monthly sales per store" dashboard typically groups by two expressions and gets `[store_id, month]` keys. ## where versus having The two clauses filter at different moments: 1. `where` runs **before** grouping and removes individual sales rows, for example refunded ones. 2. `GROUP BY` collapses the remaining rows into one row per group. 3. `having` runs **after** aggregation and removes whole groups based on an aggregate. ```ruby Sale.where(refunded_at: nil) .group(:store_id) .having("SUM(sales.amount) > ?", 50_000) .sum(:amount) ``` `having` takes the same argument forms as `where`, including `?` placeholders, so the threshold is bound rather than interpolated. A condition on the aggregate must go in `having`; SQL does not allow aggregates in `WHERE`. Active Record's own documentation pairs `having` with a `group`, and that is how report code should use it. ## group accumulates, regroup replaces Relations are composable, and `group` **appends**: `Sale.group(:store_id).group(:status)` groups by both columns. That is a surprise when a scope or a base relation already carries a `group` and a report wants a different breakdown: - `base = Sale.group(:store_id)` then `base.group(:status).count` gives counts per store and status. - `base.regroup(:status).count` gives counts per status only. - `regroup(...)` is shorthand for `unscope(:group).group(...)` and replaces the entire `GROUP BY`, not just one column. It was added in Rails 7.1. ## Ordering and limiting groups A grouped calculation keeps the relation's `order` and `limit`, which is how a "top five stores this month" widget is written in one query: ```ruby Sale.where(sold_on: Date.current.all_month) .group(:store_id) .order(Arel.sql("SUM(sales.amount) DESC")) .limit(5) .sum(:amount) ``` The `ORDER BY` names the aggregate expression rather than a column; wrapping it in `Arel.sql` declares it trusted SQL, so it keeps working even when the expression grows past the simple forms Active Record accepts unwrapped. The `LIMIT` applies to grouped rows, so the Hash holds at most five stores. Without an `order`, which groups come back first is up to the database. ## Practical notes - `size` and `count` on a grouped relation both return a Hash of counts, which breaks code expecting an Integer; `count.size` gives the number of groups. - Loading records from a grouped relation (`Sale.group(:store_id).to_a`) is a different operation from a grouped calculation: it selects `sales.*` with a `GROUP BY`, which works only where the database accepts those ungrouped columns. - When the result needs several aggregates per group (total, count and average in one row), a single calculation method cannot return them; that is a projection with `select` or `pluck` and belongs to read-model design rather than to these shortcuts.
- Why does `Sale.group(:store).sum(:amount)` run two queries while `group(:store_id)` runs one?Grouping by a `belongs_to` association name groups by its foreign key in SQL, then Active Record loads the matching `Store` records with a second `WHERE id IN (...)` query so it can use the records as Hash keys. Grouping by `:store_id` keeps the raw ids as keys and needs no second query.
- A base relation already groups by store_id. How do you get totals per status only?Call `regroup(:status)`, which discards the existing `GROUP BY` and groups by status alone. Chaining `group(:status)` would append and group by store and status together. Before Rails 7.1 the same effect needed `unscope(:group).group(:status)`.
- a grouped sum returns an Array of Sale records with a total attribute
- a condition on SUM(amount) belongs in where, not having
- calling group twice replaces the first grouping
- regroup removes only the column you name and keeps the others
- stores with no sales appear in the grouped Hash with a 0 total
Assumes Rails 8.1; regroup exists since Rails 7.1, so older apps write unscope(:group).group(...) instead.