sort by / order by

sort by orders the rows by one or more columns. order by is the same operator under another name.

SigninLogs
| summarize Failures = count() by IPAddress
| sort by Failures

The default is descending. Without asc or desc, KQL sorts from the largest value to the smallest, the newest time to the oldest, and Z to A. This is the opposite of SQL’s ORDER BY, and a classic mistake when you build a timeline: sort by TimeGenerated puts the latest event first. Write asc for oldest first.

Several keys

Separate them with commas. The second key only decides the order of rows that are equal on the first:

| sort by Computer asc, TimeGenerated asc

Each key takes its own asc or desc. A key without one is descending, even if the key before it says asc.

Nulls

Empty numbers and dates (nulls) go first in ascending order and last in descending order. You can change that with nulls first or nulls last after the direction.

Things to know

  • Results that aren’t sorted come back in no particular order, even if they look ordered. If order matters, end the query with sort by.
  • For “the N largest”, top is shorter than sort by followed by take.

Examples

1 The default order is descending
SigninLogs
| summarize SignIns = count() by Location
| sort by SignIns

No asc or desc, so the biggest count comes first.

2 Two sort keys, both ascending
SigninLogs
| summarize SignIns = count() by AppDisplayName, ClientAppUsed
| sort by AppDisplayName asc, SignIns asc

Each key has its own direction. Writing asc once does not apply to the other keys.

3 A timeline, oldest first
AuditLogs
| where OperationName == "Reset user password"
| project TimeGenerated, Identity, Result
| order by TimeGenerated asc

Practice it