Column averages
Compute a scalar average for a numeric table column in a select query.
Drizzle ORM · Function
avg is Drizzle ORM’s aggregate helper for calculating the arithmetic mean of all non-null values in a selected expression. Use it in core select queries, and group non-aggregated columns when they appear alongside the average.
The avg helper creates an SQL AVG aggregate for a selected expression. Pass it a table column or another SQL expression, and alias the selected result when a descriptive output name is useful.
avg(expression)| Name | Type | Description |
|---|---|---|
expression | SQL expression | The column or SQL expression whose non-null values are averaged. |
A selected SQL aggregate representing the arithmetic mean of all non-null values in the expression.
import { avg } from "drizzle-orm";
const result = await db
.select({ averageId: avg(users.id) })
.from(users);Selects the arithmetic mean of all non-null values in users.id.
Compute a scalar average for a numeric table column in a select query.
Summarize grouped records by selecting avg alongside grouping columns.
Calculate an average over a custom SQL expression when the built-in helper does not express the required expression.
avg is a wrapped SQL aggregate helper imported from drizzle-orm. It returns the arithmetic mean of all non-null values in the supplied expression.
Follow-up: How would you express the same operation without the helper? Use sqlavg(${users.id}).mapWith(String) in the selected field.
Use avg(column) inside db.select, such as db.select({ value: avg(users.id) }).from(users). The selected object gives the aggregate a usable result key.
Follow-up: How would you calculate a distinct average? Replace avg with avgDistinct, which emits AVG(DISTINCT expression).
If a query selects avg together with other columns, group the non-aggregated columns with .groupBy(). This follows the SQL grouping rule for aggregate queries.
Follow-up: Where should an aggregate be placed when using relational queries? The documentation says aggregations are not supported in extras, so use core queries.
avgDistinctcountsumgroupByhavingsql