sort

Use the `sort` stage to identify the sort order for records returned in the result set.

## Syntax

```sql
sort asc|desc <field1>[, asc|desc <field2>...]
```

## Parameters

| Name | Type | Required | Description |
| ------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `asc` | keyword | No | Sorts records in ascending order (lowest to highest). |
| `desc` | keyword | No | Sorts records in descending order (highest to lowest). |
| `field` | string | Yes | Specifies one or more fields to sort by. If multiple fields are provided, records are sorted in the order the fields are specified. |

## Returns

The `sort` stage returns the query result set organized according to the specified order.

## Usage notes

* Be aware that the `union` and `join` stages do not preserve sort order. If you require a specific sort order after combining datasets, always place the `sort` stage **after** your `union` or `join` stage.
* For correct sorting results when a query includes strings representing numbers, it is recommended to convert all string fields to integers or numbers (for example, using `to_integer()` or `to_number()` functions) before applying the `sort` stage.
* When sorting by multiple columns, while the sort operation is saved correctly, the user interface will only display the results according to the first sorted column.
* Sort operations can concentrate data on a single worker, which for large datasets might exceed its capacity. Including a `limit` stage after a `sort` stage can help reduce the maximum memory a worker needs to devote to the sort task, thereby improving performance.

## Examples

### Example 1: Single field sort (ascending)

**Goal**: Sorts records by `event_id` in ascending order.

**XQL code**:

```sql
dataset = sample_xql_raw
| sort asc event_id
| fields event_id, event_description
```

**Explanation**: This query sorts the events by their unique `event_id` in ascending order (lowest to highest).

**Output**:

| EVENT\_ID | EVENT\_DESCRIPTION |
| --------- | ------------------------------ |
| 101 | User login successful |
| 102 | File access attempt |
| 103 | Network connection established |
| 104 | System heartbeat |
| 105 | Data transformation |
| 106 | Unauthorized access detected |
| 107 | Cloud resource modification |
| 108 | Software update initiated |
| 109 | API request throttled |
| 110 | Database backup completed |

### Example 2: Single field sort (descending)

**Goal**: Sorts records by `duration_seconds` in descending order.

**XQL code**:

```sql
dataset = sample_xql_raw
| sort desc duration_seconds
| fields event_id, event_description, duration_seconds
```

**Explanation**: This example sorts events by `duration_seconds` in descending order, showing the longest duration events first.

**Output**:

| EVENT\_ID | EVENT\_DESCRIPTION | DURATION\_SECONDS |
| --------- | ------------------------------ | ----------------- |
| 110 | Database backup completed | 60.0 |
| 108 | Software update initiated | 15.3 |
| 103 | Network connection established | 10.2 |
| 107 | Cloud resource modification | 7.8 |
| 105 | Data transformation | 5.0 |
| 106 | Unauthorized access detected | 2.1 |
| 101 | User login successful | 1.5 |
| 102 | File access attempt | 0.8 |
| 104 | System heartbeat | 0.1 |
| 109 | API request throttled | 0.05 |

### Example 3: Multiple field sort

**Goal**: Sorts records by `is_successful` (desc) then `duration_seconds` (asc).

**XQL code**:

```sql
dataset = sample_xql_raw
| sort desc is_successful, asc duration_seconds
| fields event_id, event_description, is_successful, duration_seconds
```

**Explanation**: This example first sorts by `is_successful` (placing `true` results first due to descending sort order on boolean), and then by `duration_seconds` in ascending order for events with the same `is_successful` status.

**Output**:

| EVENT\_ID | EVENT\_DESCRIPTION | IS\_SUCCESSFUL | DURATION\_SECONDS |
| --------- | ------------------------------ | -------------- | ----------------- |
| 104 | System heartbeat | true | 0.1 |
| 101 | User login successful | true | 1.5 |
| 105 | Data transformation | true | 5.0 |
| 107 | Cloud resource modification | true | 7.8 |
| 103 | Network connection established | true | 10.2 |
| 108 | Software update initiated | true | 15.3 |
| 110 | Database backup completed | true | 60.0 |
| 109 | API request throttled | false | 0.05 |
| 102 | File access attempt | false | 0.8 |
| 106 | Unauthorized access detected | false | 2.1 |

### Example 4: Numeric conversion sort

**Goal**: Extracts a numeric code from JSON and sorts by it in ascending order.

**XQL code**:

```sql
dataset = sample_xql_raw
| alter status_code = to_number(coalesce(json_extract_scalar(simple_json_data, "$.code"), json_extract_scalar(simple_json_data, "$.error_code")))
| filter status_code != null // Ensure we only sort non-null numeric codes
| sort asc status_code
| fields event_id, event_description, simple_json_data, status_code
```

**Explanation**: This example demonstrates how to extract a numeric value (either `code` or `error_code`) from the `simple_json_data` JSON field, convert it to a number using `to_number()`, and then sort by it. This ensures numeric sorting rather than string sorting (for example, ensuring 200 comes before 429).

**Output**:

| EVENT\_ID | EVENT\_DESCRIPTION | SIMPLE\_JSON\_DATA | STATUS\_CODE |
| --------- | --------------------- | ------------------------------------------------------ | ------------ |
| 101 | User login successful | {"status": "ok", "code": 200} | 200 |
| 109 | API request throttled | {"error\_code": 429, "message": "Rate limit exceeded"} | 429 |

## Related articles

* **Stages**: [`limit`](limit), [`join`](join), [`union`](union)
* **Functions**: [`to_number`](../functions/to_number), [`to_integer`](../functions/to_integer)
* **Datasets**: [`xdr_data`](https://www.google.com/search?q=%5Bhttps://docs-cortex.paloaltonetworks.com/r/Cortex-XQL-Schema-Reference-Guide/Introduction%5D\(https://docs-cortex.paloaltonetworks.com/r/Cortex-XQL-Schema-Reference-Guide/Introduction\))