Compute a table-wide maximum
Find the greatest identifier, number, date, or other comparable column value in a table.
Drizzle ORM · Function
max is Drizzle ORM's aggregate helper for selecting the greatest value of a column or SQL expression. It is used inside a select projection and corresponds to SQL MAX.
Use max with a column or SQL expression inside a select projection. Drizzle emits the SQL MAX aggregate and returns the selected maximum under the alias you provide; for custom SQL, map the result with the column's decoder.
max(expression)| Name | Type | Description |
|---|---|---|
expression | SQL expression | The column or SQL expression whose greatest value should be calculated. |
A SQL aggregate expression representing the maximum value of the supplied expression.
import { max } from "drizzle-orm";
import { users } from "./schema";
const result = await db
.select({ value: max(users.id) })
.from(users);Selects the maximum value of the users.id column.
Find the greatest identifier, number, date, or other comparable column value in a table.
Select grouped records and calculate the greatest value within each group.
Represent a MAX operation while retaining a column's result decoder.
max is an aggregate helper imported from drizzle-orm. In a select projection, max(users.id) generates SQL equivalent to MAX(id) and returns the maximum value.
Follow-up: How would you preserve Drizzle's result mapping for a custom expression? Use sql with max and mapWith, passing the relevant column or decoder.
The helper accepts an expression, commonly a table column, and is used in a select projection such as db.select({ value: max(users.id) }).from(users). The result is exposed through the projection key.
Follow-up: What SQL does the helper represent? It represents the database MAX aggregate over the supplied expression.
If an aggregate is selected alongside ordinary columns, the ordinary columns must be grouped with groupBy, following SQL aggregation rules. The documentation also shows filtering grouped aggregates with having.
Follow-up: Can max be placed in relational-query extras? No; the documentation says aggregations are not currently supported there, so use core queries.
minavgsumcountsumDistinctsqlgroupByhaving