Skip to main content

avg

The avg method returns the average (arithmetic mean) of a set of numeric values:

const avgOfAllScoresForAllGames = await Game.avg('score')

select avg("score") from "games"

NOTE: You must pass a column that can be averaged, such as an integer or decimal. Averaging non-numeric columns will result in runtime exceptions.

Chaining

You can leverage chainable methods to filter out records at the SQL level before calling avg:

const sportsballScoresAvg = await Game.where({ type: 'sportsball' }).avg('score')

select avg("score") from "games" where ("games"."type" ilike $1)

Grouped averages: avgBy

avg collapses the whole query to a single number. When you need the average broken out per group in one query, use avgBy(groupColumn, aggregatedColumn). It stays entirely in Dream — no ejecting to Kysely and no hand-written GROUP BY — and returns Map<groupValue, average>:

const avgScoreByType = await Game.avgBy('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.