Splunk online course

Splunk sort Command: Sort Search Results by Field

Learn Splunk's sort command syntax, ascending and descending order, multiple sort keys, result limits, numeric sorting, and practical SPL examples.

The Splunk sort command orders search-result events or rows by one or more field values. You can use it to arrange categories alphabetically, find the largest or smallest values, rank summary results, or make a table easier to inspect.

Prerequisites: You should know basic SPL syntax, the pipe character, fields, and the general use of stats and where. If you need a refresher, see Splunk fields and SPL pipes.

What the sort command does

sort is a search-pipeline command that orders the results produced by the part of the search before it. A sort key is a field used to determine that order.

Sorting is most useful when you need to:

  • Find the highest or lowest numerical values.
  • Arrange text categories alphabetically or in reverse alphabetical order.
  • Rank rows created by an aggregation such as stats.
  • Make ties predictable by adding additional sort keys.

Sort is commonly used after fields have been extracted, calculated with eval, or produced by a command such as stats. It can sort raw events, but it can also sort the summary rows returned by an aggregation.

Basic sort syntax

The basic form places sort after a pipe and supplies a field name:

base search | sort <field-name>

For example:

index=products | sort categoryId

The pipe sends the results of index=products to sort. Because no direction marker is present, the results are sorted in ascending order.

Syntax and direction at a glance

SyntaxMeaningExample use
| sort fieldSort by field in ascending order.| sort categoryId
| sort -fieldSort by field in descending order.| sort -count
| sort count fieldReturn up to count sorted results.| sort 10 -count
| sort 0 fieldRequest all available results in sorted order.| sort 0 categoryId
| sort field1 -field2Use mixed directions for multiple sort keys.| sort categoryId -count

Ascending order

Ascending order means ordering from lower to higher values. It is the default direction for sort, so a field name without a minus sign sorts ascending.

index=products | sort categoryId

For a text field such as categoryId, alphabetically earlier values appear first. A possible order is:

ACCESSORIES
BOOKS
SHOES
TEE

For numeric values, ascending order is intended to go from the smallest number to the largest. For timestamps, earlier times appear before later times when the timestamp field is represented appropriately for time comparison.

Descending order

Descending order means ordering from higher to lower values. Put a minus sign directly before the field name:

| sort -<field-name>

For example:

index=products | sort -categoryId

This reverses the alphabetical order. A later value such as TEE can appear before an earlier value such as ACCESSORIES.

TEE
SHOES
BOOKS
ACCESSORIES

For a numeric field, descending order places the largest values first. This makes it useful for ranking counts, response times, sizes, and other measurements.

Sorting multiple fields

You can provide several field names. Splunk uses them in priority order:

  • The primary sort key is the first field and controls the main ordering.
  • A secondary sort key is used when two or more rows have the same primary value.
  • Each field can have its own direction by placing a minus sign before fields that should be descending.
index=products | stats count by categoryId, productName | sort categoryId -count

This sorts summary rows by categoryId in ascending order. Within each category, rows with the largest count appear first.

For example, the rows might be ordered like this:

ACCESSORIES  42
ACCESSORIES  17
TEE          31
TEE          12

Here, categoryId is the primary sort key and count is the secondary sort key. Adding a secondary key is also useful when deterministic ordering matters and several rows have identical primary values.

Sort result limits

sort has a result limit. If you do not specify a count, Splunk uses its default sort limit, commonly 10,000 results. Therefore, a search can have more matching results than the rows that are sorted and returned by sort.

Put a positive count before the sort fields to request a limited number of sorted results:

index=products | stats count by categoryId | sort 5 -count

This returns the five categories with the largest event counts. The operation is a top N query: N is the number of highest-ranked results you want.

Use 0 when all available results should be sorted:

index=products | sort 0 categoryId

A positive count limits the returned sorted results. A count of 0 requests an unrestricted sorted result set, but sorting a large number of rows can consume more time and resources. Use a limited sort when you only need a ranking such as the top five or top ten.

Sort behavior by data type

Sort comparisons depend on how field values are represented. A field extracted as text can be compared as a string, even when its contents look like numbers. String comparison examines characters from left to right, which can produce this order:

1
10
2

That is different from numerical order, where 1, 2, and 10 would be expected.

When numerical ranking is intended, ensure that the field is numeric before sorting. Check the field extraction and any conversion steps. If the original value is text, create a numeric derived field when appropriate:

index=products
| eval numeric_value=tonumber(value)
| sort -numeric_value

Then inspect the resulting field and confirm that the order reflects numerical values. The same principle applies to timestamps and other values whose correct ordering depends on representation.

Where sort belongs in an SPL pipeline

Sort aggregated rows after stats

stats aggregates events into calculated summary rows. Sorting after stats ranks those rows rather than the original events:

index=products
| stats count by categoryId
| sort -count

This produces one row per category and places the category with the highest count first. Learn more about aggregation with the Splunk stats command.

Filter before sorting

Use where to remove rows that do not qualify before ordering the remainder:

index=products
| stats count by categoryId
| where count > 10
| sort -count

This keeps only categories with more than ten events, then ranks the qualifying categories from largest to smallest. Filtering first avoids spending sorting work on irrelevant rows. See the Splunk where command for expression-based filtering.

Sort raw events

You can sort events directly when the field is present on each event:

index=products | sort -price

This orders event rows by price. In contrast, the following sorts summary rows created by stats:

index=products | stats avg(price) as average_price by categoryId | sort -average_price

The second search ranks categories by their calculated average rather than ordering individual events.

Common sorting patterns

ObjectiveSPL patternResult
Alphabetical ordering| sort categoryIdEarlier category values appear first.
Reverse alphabetical ordering| sort -categoryIdLater category values appear first.
Top-N counts after stats| stats count by categoryId | sort 5 -countThe five categories with the greatest counts are returned.
Multi-field tie breaking| sort categoryId -countCategories sort ascending; equal categories rank by count descending.
Filtering with where before sort| where count > 10 | sort -countOnly qualifying rows are ranked.

Inspecting and validating sort results

If the order does not look correct, validate the field and the direction rather than assuming that sort failed.

  1. Check that the named sort field is extracted or created before the sort command.
  2. Display the field with a table or fields step so you can inspect its values.
  3. Confirm whether the field contains text, numbers, timestamps, null values, or identical values.
  4. Check whether a minus sign is present for descending order.
  5. Add a secondary sort key when rows tie on the primary key.
  6. Check the result limit if fewer rows appear than expected.
index=products
| stats count by categoryId
| table categoryId count
| sort -count

The displayed columns make it easier to verify both the sort field and the resulting order. If several rows have the same count, add another key, for example sort -count categoryId, to make the tie order consistent.

Troubleshooting sort searches

The results are in the opposite direction

The likely cause is that the minus sign was omitted or placed incorrectly. Use the minus sign immediately before the field name:

| sort -count

Only part of the expected result set appears

The sort result limit may be restricting the output. Use a suitable positive count for top-N analysis, or use 0 when every available result must be sorted:

| sort 10 -count
| sort 0 categoryId

Use an unrestricted sort carefully on a broad search because it may require ordering many rows.

Numbers sort as 1, 10, 2

The values are probably being treated as text. Inspect the extraction and convert the field to a numeric representation before sorting, such as with tonumber in eval.

The visible order does not change

The field may be missing, null for most results, or identical across the displayed rows. Use table or fields to verify that the field exists and contains useful values. Add a secondary key if the primary values tie.

Sorting is slow

Sorting a large number of raw events can be expensive. Narrow the time range, add suitable base-search filters, filter earlier with where, aggregate with stats when summary rows are sufficient, and use a top-N limit when full ordering is unnecessary.

Exam-relevant notes

  • | sort field is ascending by default.
  • | sort -field is descending.
  • Multiple fields are evaluated from left to right as primary, secondary, and later sort keys.
  • A positive count limits the number of sorted results.
  • sort 0 requests all results, but may require more resources.
  • Sorting after stats ranks aggregate rows, not individual source events.
  • For numerical ranking, confirm that the sort field is numeric rather than numeric-looking text.

Practice examples

Sort categories alphabetically

index=products | sort categoryId

This uses the default ascending order for the text field categoryId.

Sort categories in reverse alphabetical order

index=products | sort -categoryId

This places later alphabetic values, such as TEE, before earlier values such as ACCESSORIES.

Find the five categories with the most events

index=products
| stats count by categoryId
| sort 5 -count

The search first creates counts, then returns the five largest counts.

Sort summary rows with a tie breaker

index=products
| stats count by categoryId, productName
| sort categoryId -count

Categories are ordered ascending, and products within each category are ordered by count descending.

Sort every available result

index=products | sort 0 categoryId

Use this when the default result limit is not sufficient and you genuinely need the complete ordered set.

Summary

The sort command orders events or rows by field values. Use a plain field name for ascending order, a minus sign for descending order, and multiple fields for primary and secondary ordering. Apply it after fields or summaries have been created, filter irrelevant rows before sorting, and choose a result limit that matches the question. Finally, validate the field's data type and displayed values so that the resulting order represents the analysis you intended.