Basic ascending or descending sorting
Sort records by newest or oldest timestamps, names, IDs, or other columns.
Drizzle ORM · Module
.orderBy() controls result ordering in Drizzle's core query builder. Relational queries also support ordering objects, callbacks, and custom SQL expressions.
In Drizzle's core query builder, call .orderBy() after selecting the source rows and optionally filtering them. Pass column expressions such as asc(column) or desc(column); for ordering features not directly represented by the API, pass an sql expression instead.
query.orderBy(...columns)| Name | Type | Description |
|---|---|---|
...columns | SQL.Asc | SQL.Desc | SQL | column ordering expressions | One or more column ordering expressions, such as asc(column), desc(column), or a custom sql expression; relational-query forms may also use an ordering object or callback. |
A query builder configured with an SQL ORDER BY clause; executing it returns rows in the specified order.
order by operator available through the callback.import { desc, eq } from 'drizzle-orm';
import { db } from './db';
import { posts } from './schema';
const rows = await db
.select()
.from(posts)
.where(eq(posts.authorId, 1))
.orderBy(desc(posts.createdAt));Fetches matching posts with the newest records first.
Sort records by newest or oldest timestamps, names, IDs, or other columns.
Add a database-specific ordering expression such as NULL placement.
Define primary and secondary sorting for stable results.
Apply independent ordering to parent and nested relational results.
Use .orderBy() with ordering expressions such as asc(column) or desc(column) in the core query builder. The documentation also shows that a custom sql expression can be supplied when more specific ordering behavior is needed.
Follow-up: How would you express NULL ordering? Pass a custom SQL expression, for example sql\${users.id} desc nulls first\.
orderBy work in relational queries?In relational queries, orderBy can use an object such as { id: "asc" }. It can also use a callback, whose table argument represents the current query scope.
Follow-up: Why is the callback argument required in nested queries? It exposes the aliased table for that scope, enabling correct SQL generation.
Multiple orderBy clauses on the same table appear in the generated query in the same order they were added. This lets you define deterministic primary and secondary sorting.
Follow-up: How can you add ordering behavior not directly provided by Drizzle? Use the sql template in the ordering expression.
ascdescsqlwherefindMany