Skip to content

Order

You can order results returned by Appwrite Databases by using an order query. For best performance, create an index on the column you plan to order by.

Ordering one column

When querying using the listDocuments endpoint, you can specify the order of the documents returned using the Query.orderAsc() and Query.orderDesc() query methods.

import { Client, Databases, Query } from "appwrite";

const client = new Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>');

const databases = new Databases(client);

databases.listDocuments(
    '<DATABASE_ID>',
    '<COLLECTION_ID>',
    [
        Query.orderAsc('title'),
    ]
);

Multiple columns

To sort based on multiple attributes, simply provide multiple query methods. For better performance, create an index on the first attribute that you order by.

In the example below, the movies returned will be first sorted by title in ascending order, then sorted by year in descending order.

// Web SDK code example for sorting based on multiple attributes
// ...

// List documents and sort based on multiple attributes
databases.listDocuments(
    '<DATABASE_ID>',
    '<COLLECTION_ID>',
    [
        Query.orderAsc('title'), // Order first by title in ascending order
        Query.orderDesc('year'), // Then, order by year in descending order
    ]
);

Ordering by sequence

For numeric ordering based on insertion order, you can use the $sequence field, which Appwrite automatically adds to all documents. This field increments with each new insert.

import { Client, Databases, Query } from "appwrite";

const client = new Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>');

const databases = new Databases(client);

databases.listDocuments(
    '<DATABASE_ID>',
    '<COLLECTION_ID>',
    [
        Query.orderAsc('$sequence'),
    ]
);

The $sequence field is useful when you need:

  • Consistent ordering for pagination, especially with high-frequency inserts
  • Reliable insertion order tracking when timestamps might not be precise enough
  • Simple numeric ordering without managing custom counter fields