# Override sorting behavior

{% hint style="success" %}
This is the official documentation of the `@forestadmin/agent` Node.js agent.
{% endhint %}

Depending on the data source, not all fields may be sortable, or you may want to change how the native sorting works.

By using the `replaceFieldSorting` and `emulateFieldSorting` methods, you can change a single column's sorting behavior.

#### Substitution

You can also provide replacement sort clauses. In this example, we're telling Forest Admin "When a user sorts by full name, I want to sort by the last name, and then by the first name".

```javascript
collection.replaceFieldSorting('fullName', [
  { field: 'lastName', ascending: true },
  { field: 'firstName', ascending: true },
]);
```

Another very common reason is performance. For instance, with auto-incrementing ids, sorting by `creationDate` is equivalent to sorting by the primary key in reverse order.

Using sort substitution where needed can save you from adding many indexes to your database.

```javascript
// Sorting by creationDate ascending <=> Sorting by id descending
collection.replaceFieldSorting('creationDate', [{ field: 'id', ascending: false }]);
```

#### Emulation

Sorting emulation allows making any field automatically sortable. It will sort records by lexicographical order. It is a convenient way to get things working quickly for Collections that have a low number of records (in the thousands at most).

{% hint style="warning" %}
This emulation forces the Agent to retrieve all the Collection records and compute the field values for each one of them. As a consequence, sorting emulation performance cost is **linear** with the number of records in the Collection, so **activate it sparingly and with great care**.
{% endhint %}

```javascript
collection.emulateFieldSorting('fullName');
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/developer-guide-agents-nodejs/agent-customization/fields/sort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
