---
title: "Queries — Sort"
aliases: [payload-sort, payload-query-sort]
tags: [payloadcms, queries, sort, api]
sources: [raw/queries__sort.md]
created: 2026-05-15
updated: 2026-05-15
---

## Overview

Documents can be sorted by any **top-level stored field**. Prefix with `-` for descending order; no prefix = ascending.

> **Constraint:** Virtual fields cannot be used for sorting unless [[wiki/payloadcms/fields-relationship|linked with a relationship field]]. The field must exist in the database.

> **Performance:** Enable `index: true` on fields you sort by. See [[wiki/payloadcms/database-indexes|Database Indexes]].

---

## Local API

```ts
// Single field — ascending
const posts = await payload.find({
  collection: 'posts',
  sort: '-createdAt',           // descending
})

// Multiple fields
const posts = await payload.find({
  collection: 'posts',
  sort: ['priority', '-createdAt'],  // array of strings
})
```

---

## REST API

```
GET /api/posts?sort=-createdAt
GET /api/posts?sort=priority,-createdAt    // comma-separated
```

Using `qs-esm` query string builder (array form):

```ts
import { stringify } from 'qs-esm'

const query = stringify({ sort: ['priority', '-createdAt'] }, { addQueryPrefix: true })
fetch(`/api/posts${query}`)
```

---

## GraphQL API

```graphql
# Single field
query {
  Posts(sort: "-createdAt") {
    docs { color }
  }
}

# Multiple fields — comma-separated string
query {
  Posts(sort: "priority,-createdAt") {
    docs { color }
  }
}
```

---

## Syntax Summary

| Context | Multiple fields | Descending prefix |
|---------|----------------|-------------------|
| Local API | Array of strings | `-fieldName` |
| REST API | Comma-separated string or array | `-fieldName` |
| GraphQL | Comma-separated string | `-fieldName` |

---

## Key Takeaways

- `-fieldName` = descending; `fieldName` = ascending — works across all three APIs
- Local API accepts an **array**; REST/GraphQL accept a **comma-separated string** (REST also accepts array via qs)
- Only **stored fields** are sortable — virtual fields require a relationship link to be sortable
- Add `index: true` to sort fields for query performance; compound sorts benefit from compound indexes (see [[wiki/payloadcms/database-indexes|Database Indexes]])
- Sort is complementary to [[wiki/payloadcms/queries-pagination|pagination]] and [[wiki/payloadcms/queries-select|select/populate]]

---

## Sources

- `raw/queries__sort.md` — https://payloadcms.com/docs/queries/sort
