Aggregate per group
Summarize records by a category, project, or other column.
Drizzle ORM · Module
.groupBy adds grouping criteria to a Drizzle select query and generates SQL GROUP BY. It is commonly used with aggregate expressions, with .having available to filter groups.
.groupBy adds SQL GROUP BY criteria to a select query. Pass columns or SQL expressions to define the grouping key, and combine aggregate selections with .having when filtering grouped results.
.groupBy(...columns)| Name | Type | Description |
|---|---|---|
columns | Column or SQL expression(s) | Columns or SQL expressions that determine which rows belong to the same group. |
A select query builder that emits a SQL GROUP BY clause.
.groupBy after .from and pass one or more table columns as grouping criteria..groupBy when grouping by an expression rather than a plain column..mapWith(Number)..groupBy when the query requires grouping behavior not directly represented by the standard builder.import { sql } from 'drizzle-orm';
import { usersTable } from './schema';
const rows = await db
.select({
projectId: usersTable.projectId,
count: sql<number>`count(${usersTable.id})`.mapWith(Number),
})
.from(usersTable)
.groupBy(usersTable.projectId)
.having(sql`count(${usersTable.id}) > 300`);Groups users by project and keeps only groups containing more than 300 users.
Summarize records by a category, project, or other column.
Retain only groups meeting an aggregate threshold.
Express grouping logic that needs custom SQL.
.groupBy do?.groupBy adds a GROUP BY clause to a select query. It receives the columns or SQL expressions that define each group.
Follow-up: How can grouped results be filtered? Use .having, typically with an aggregate SQL expression such as a count condition.
.groupBy accompany aggregate functions?When a query selects aggregate values and ordinary columns, the ordinary selected columns need to be represented in the grouping criteria. Drizzle emits the corresponding SQL GROUP BY clause.
Follow-up: What should you do when the grouping expression is not directly available? Pass an sql template expression to .groupBy.
.groupBy?The builder accepts SQL expressions, so sql can be used directly in a GROUP BY clause. This supports grouping behavior that needs custom SQL while retaining the query builder.
Follow-up: Can the same SQL expression be used in HAVING? Yes; the documentation demonstrates an aggregate count expression in .having.
selectfromhavingsqlmapWith