The sort operator in APL arranges the rows of a result set based on one or more fields in ascending or descending order. You can use it to organize your data logically or optimize subsequent operations that depend on ordered data. This operator is useful when analyzing logs, traces, or any dataset where the order of results matters, such as when you’re interested in top or bottom performers, chronological sequences, or sorting by status codes.

For users of other query languages

If you come from other query languages, this section explains how to adjust your existing queries to achieve the same results in APL.

Usage

Syntax

| sort by Field1 [asc | desc], Field2 [asc | desc], ...

Parameters

  • Field1, Field2, …: The fields to sort by.
  • [asc | desc]: Specify the sorting direction for each field as either asc for ascending order or desc for descending order.

Returns

A table with rows ordered based on the specified fields.

Use sort and project together

When you use project and sort in the same query, ensure you project the fields that you want to sort on. Similarly, when you use project-away and sort in the same query, ensure you don’t remove the fields that you want to sort on.

The above is also true for time fields. For example, to project the field status and sort on the field _time, project both fields similarly to the query below:

['sample-http-logs']
| project status, _time
| sort by _time desc

Use case examples

Sorting HTTP logs by request duration and then by status code is useful to identify slow requests and their corresponding statuses.

Query

['sample-http-logs']
| sort by req_duration_ms desc, status asc

Run in Playground

Output

_timereq_duration_msidstatusurimethodgeo.citygeo.country
2024-10-18 12:34:565000abc1500/api/dataGETNew YorkUS
2024-10-18 12:35:564500abc2200/api/usersPOSTLondonUK

The query sorts the HTTP logs by the duration of each request in descending order, showing the longest-running requests at the top. If two requests have the same duration, they are sorted by status code in ascending order.

  • top: Use top to return a specified number of rows with the highest or lowest values, but unlike sort, top limits the result set.
  • project: Use project to select and reorder fields without changing the order of rows.
  • extend: Use extend to create calculated fields that can then be used in conjunction with sort to refine your results.
  • summarize: Use summarize to group and aggregate data before applying sort for detailed analysis.