---
title: Sorting
description: Order query results using orderBy
icon: arrow-up-down
---

## Basic Sorting

```ts
// 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:

```ts
// 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:

```ts
// 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" },
  },
});
```

:::info
`nulls: "first" | "last"` controls where null values land in the order, and works the same on every database.
:::

## Vector Distance Sorting

Sort vector scalars by distance to a query vector:

```ts
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:

```ts
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`:

```ts
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
```

The order is exact, even when the column has a nearest-neighbour index. Add
`approximate: true` to let such an index answer a nearest-first root read with
`take`: faster, approximate, and possibly fewer rows than `take`. See
[Approximate nearest neighbours](/docs/schema/scalars/vector#approximate-nearest-neighbours).

:::warning
Vector distance sorting requires a pgvector-enabled PostgreSQL driver, for example `new PgDriver({ pgvector: true })`. Other drivers throw `FeatureNotSupportedError`, and the `to` vector length must match the scalar dimension.
:::

## GeoPoint Distance Sorting

Full-tier GeoPoint providers order by spherical meters with the same computed
`_distance` output:

```ts
const paris = { longitude: 2.3522, latitude: 48.8566 };

const nearest = await client.place.findMany({
  select: {
    id: true,
    location: { _distance: { to: paris } },
  },
  orderBy: {
    location: { _distance: { to: paris, sort: "asc" } },
  },
  take: 10,
});
```

`"asc"` is nearest-first and `"desc"` is farthest-first. Null points sort last
in both directions. PostgreSQL requires proven PostGIS; MySQL2 is full tier;
SQLite-family providers refuse distance compilation. See
[GeoPoint](/docs/schema/scalars/point#select-and-order-by-distance).

## Relation Sorting

Sort by a scalar field of a to-one relation:

```ts
// 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" },
      },
    },
  },
});
```

:::info
Relation sorting follows to-one relations up to eight relation hops; a
  ninth is rejected before SQL generation. To-many relations in the middle of
  a sort path are rejected too; use `_count` aggregate sorting for to-many
  relations instead.
:::

## Aggregate Sorting

Sort by relation count:

```ts
// 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

Included rows come back in the order you ask for, and in no particular order
when you ask for none: like a SQL query without `ORDER BY`, VibORM spends
nothing sorting rows no one asked to sort. Give an `orderBy` wherever the
order matters, in an `include` or a `select` at any depth. A `take`, `skip`,
`cursor` or `distinct` on included rows always reads them in a stable order
(yours, then the related model's key), so the page they pick is the same each
time; so does an `ordering` extension's or a `defaults` extension's order.

Sort included relations:

```ts
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) |
