Sorting
Order query results using orderBy
Basic Sorting
// Ascending (default)
const users = await client.user.findMany({
orderBy: { name: "asc" },
});
// Descending
const users = await client.user.findMany({
orderBy: { createdAt: "desc" },
});
Multiple Scalars
Sort by multiple fields:
// Array syntax
const users = await client.user.findMany({
orderBy: [
{ lastName: "asc" },
{ firstName: "asc" },
],
});
// Sort by role then name
const users = await client.user.findMany({
orderBy: [
{ role: "asc" },
{ name: "asc" },
],
});
Null Handling
Control where nulls appear:
// Nulls first
const users = await client.user.findMany({
orderBy: {
lastLogin: { sort: "desc", nulls: "first" },
},
});
// Nulls last
const users = await client.user.findMany({
orderBy: {
lastLogin: { sort: "desc", nulls: "last" },
},
});
Vector Distance Sorting
Sort vector scalars by distance to a query vector:
const queryEmbedding = [0.12, 0.34, 0.56];
const nearest = await client.document.findMany({
select: { id: true, title: true },
orderBy: {
embedding: {
_distance: {
to: queryEmbedding,
metric: "cosine", // "l2" | "cosine"
},
},
},
take: 10,
});
sort is optional. "asc" means nearest-first and is the default; "desc" means farthest-first:
const farthest = await client.document.findMany({
orderBy: {
embedding: {
_distance: {
to: queryEmbedding,
metric: "l2",
sort: "desc",
},
},
},
take: 10,
});
Select the distance score with the same _distance object. The selected score is returned as _distance: number:
const results = await client.document.findMany({
select: {
id: true,
embedding: {
_distance: {
to: queryEmbedding,
metric: "cosine",
},
},
},
orderBy: {
embedding: {
_distance: {
to: queryEmbedding,
metric: "cosine",
},
},
},
});
results[0]?._distance; // number | undefined
Relation Sorting
Sort by a scalar field of a to-one relation:
// Sort posts by author name
const posts = await client.post.findMany({
orderBy: {
author: { name: "asc" },
},
});
// Sort comments by a scalar on their post
const comments = await client.comment.findMany({
orderBy: {
post: { title: "asc" },
},
});
// Sort posts by the author's company name through a to-one chain
const posts = await client.post.findMany({
orderBy: {
author: {
team: {
company: { name: "asc" },
},
},
},
});
Aggregate Sorting
Sort by relation count:
// Most posts first
const users = await client.user.findMany({
orderBy: {
posts: { _count: "desc" },
},
});
// Most comments first
const posts = await client.post.findMany({
orderBy: {
comments: { _count: "desc" },
},
});
Sorting Included Relations
Sort included relations:
const users = await client.user.findMany({
include: {
posts: {
orderBy: { createdAt: "desc" },
take: 5,
},
},
});
Sort Direction
| Value | Description |
|---|---|
"asc" |
Ascending (A-Z, 0-9, oldest-newest) |
"desc" |
Descending (Z-A, 9-0, newest-oldest) |