sum
The sum method will sum a numeric column for all found records in the query:
const sumOfAllScoresForAllGames = await Game.sum('score')
select sum("score") from "games"
NOTE: You must pass a column that can be summed, such as an integer or decimal. Summing non-numeric types will result in runtime exceptions.
Chaining
You can leverage chainable methods to filter out records at the SQL level before calling sum:
const sportsballScoresSum = await Game.where({ type: 'sportsball' }).sum('score')
select sum("score") from "games" where ("games"."type" ilike $1)
Grouped sums: sumBy
sum collapses the whole query to a single number. When you need the sum broken out per group in one query, use sumBy(groupColumn, aggregatedColumn). It stays entirely in Dream — no ejecting to Kysely and no hand-written GROUP BY — and returns Map<groupValue, sum>:
const totalScoreByType = await Game.sumBy('type', 'score')
Only groups with at least one matching row are present in the returned Map — seed absent keys as needed — and a nullable group column produces a real null key.