> ## Documentation Index
> Fetch the complete documentation index at: https://explore.airia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sort

> Order results by one or more fields with null handling and numeric vs. lexicographic modes.

The **Sort** step takes a JSON array and reorders its items based on one or more fields. Use it to rank search results by relevance score, order invoices by date, or arrange products by price before passing the list to a model or returning it to the user.

You can sort by multiple fields (primary, secondary, etc.), choose between numeric and alphabetical ordering, and control where null values land in the result.

***

## Configuration

<Steps>
  <Step title="Input">
    An expression that resolves to a JSON array — for example, `{{Steps.Search_Results.Value}}`.
  </Step>

  <Step title="Sort criteria">
    One or more sort rules applied in order. The first criterion is the primary sort; subsequent criteria break ties.

    Each criterion has:

    * **Field path** — dot-notation path to the field (e.g., `score`, `created.date`). Leave empty to sort by the item value itself (useful for arrays of strings or numbers).
    * **Direction** — `Ascending` (A→Z, 0→9) or `Descending` (Z→A, 9→0).
    * **Comparison type** — `Lexicographic` (string/dictionary order) or `Numeric` (parse as number).
    * **Case sensitive** — toggle for lexicographic comparisons (off by default).
  </Step>

  <Step title="Null handling">
    Where to place items whose sort field is null or missing.
  </Step>

  <Step title="Missing field behavior">
    What to do when an item does not have the field at all.
  </Step>
</Steps>

***

## Sort criteria in detail

### Comparison types

| Type                        | Behaviour                                                                                               | Use when                                                 |
| --------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| **Lexicographic** (default) | Compares values as strings using dictionary order. `"9"` comes after `"10"` because `"9"` > `"1"`.      | Sorting names, statuses, categories, or any text field   |
| **Numeric**                 | Parses values as numbers. `9` correctly comes before `10`. Throws an error if a value cannot be parsed. | Sorting scores, prices, quantities, or any numeric field |

<Warning>
  If you choose **Numeric** and any item has a non-numeric value in the sort field, the step throws a runtime error. Use a [Filter](/building-and-deploying-agents/agent-basics/filter-step) step first to remove items with invalid values, or use **Lexicographic** mode and accept string ordering.
</Warning>

### Multi-field sorting

Add multiple criteria to handle ties. Criteria are applied in order — the first field is the primary sort, the second breaks ties in the first, and so on.

**Example:** Sort employees by department (ascending), then by salary (descending) within each department:

| # | Field path   | Direction  | Comparison type |
| - | ------------ | ---------- | --------------- |
| 1 | `department` | Ascending  | Lexicographic   |
| 2 | `salary`     | Descending | Numeric         |

The sort is **stable** — items that are equal on all criteria keep their original relative order.

***

## Null handling

Controls where items with `null` sort values appear in the result.

| Mode               | Behaviour                                                                            |
| ------------------ | ------------------------------------------------------------------------------------ |
| **Last** (default) | Null values are placed at the end of the result, regardless of sort direction        |
| **First**          | Null values are placed at the beginning                                              |
| **Ignore**         | Items with null values in **all** sort criteria are removed entirely from the output |

***

## Missing field behavior

Controls what happens when an item does not have the sort field at all (the field is absent, not just null).

| Mode                         | Behaviour                                                                                                                                                                      |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Preserve Order** (default) | Treat the missing field as null. Items with missing fields maintain their original relative position among other null-valued items.                                            |
| **Error**                    | Throw a runtime error identifying the item index and the missing field. Use this when your data should always have the field present — the error acts as a data quality check. |

***

## Output

The step returns a **JSON array** with the same items, reordered according to your criteria.

```
{{Steps.Sort.Value}}  →  [ ...items in new order... ]
```

If the input is empty, the output is an empty array `[]`.

***

## Use case: rank knowledge base results for a RAG agent

A retrieval-augmented generation (RAG) agent searches a knowledge base and receives results with relevance scores. Before passing them to the model, you want the most relevant results first — and you want to drop any results where the score is missing.

**Agent flow:**

```
Input → Data Store Search → Sort → Synthesise Answer (AI Model)
```

**Sort configuration:**

| Setting                | Value                                         |
| ---------------------- | --------------------------------------------- |
| Input                  | `{{Steps.Data_Store_Search.Value.documents}}` |
| Null handling          | **Ignore**                                    |
| Missing field behavior | **Preserve Order**                            |

**Sort criteria:**

| # | Field path       | Direction  | Comparison type | Case sensitive |
| - | ---------------- | ---------- | --------------- | -------------- |
| 1 | `relevanceScore` | Descending | Numeric         | —              |

**What happens at runtime:**

Given this input from the knowledge base:

```json theme={null}
[
  { "source": "FAQ", "content": "...", "relevanceScore": 0.72 },
  { "source": "Manual", "content": "...", "relevanceScore": 0.95 },
  { "source": "Blog", "content": "...", "relevanceScore": null },
  { "source": "Guide", "content": "...", "relevanceScore": 0.88 }
]
```

The Sort step returns:

```json theme={null}
[
  { "source": "Manual", "content": "...", "relevanceScore": 0.95 },
  { "source": "Guide", "content": "...", "relevanceScore": 0.88 },
  { "source": "FAQ", "content": "...", "relevanceScore": 0.72 }
]
```

* The Blog entry is dropped because its score is `null` and null handling is set to **Ignore**.
* The remaining items are ordered highest score first.
* The AI Model step receives the most relevant documents at the top of its context.

***

## Tips

<Tip>
  Pair Sort with a [Filter](/building-and-deploying-agents/agent-basics/filter-step) step upstream to first remove irrelevant items, then sort the remainder. This reduces the data the model needs to process and keeps token costs predictable.
</Tip>

<Tip>
  For date sorting, use **Lexicographic** mode on ISO 8601 formatted dates (e.g., `2026-03-26T14:30:00Z`). ISO 8601 strings sort correctly in lexicographic order because they are structured from most significant (year) to least significant (second).
</Tip>

<Info>
  The sort is stable — when two items are equal on all sort criteria, they appear in the same relative order as in the input. This is useful when you add a secondary sort and want tied items to keep their original sequence.
</Info>
