# order

Sorts in ascending or descending order on one or more fields.

## Syntax

```nolang
result = order rows by field [ asc | desc ];
result = order rows by (field [ asc | desc ], field [ asc | desc ]);
result = order rows by field [ asc | desc ] nulls [first | last];
```

`asc` or `desc` specifies whether the results are ordered in ascending (`asc`) or descending (`desc`) order. The default order is ascending.

## Usage

Use `order` to sort the results in a data stream for display. You can use `order` with ungrouped data. You can also use `order` to sort grouped data by an aggregated value.

Do not use `order` to specify the order that another SAQL statement or function will process records in. For example, do not use `order` before `timeseries` to change the order of processing. Instead, use `timeseries` parameters.

By default, nulls are sorted last when sorting in ascending order and first when sorting in descending order. You can change the ordering of nulls using nulls `[first | last]`.

:::note
Applying labels to dimension values in the XMD changes the displayed values, but doesn’t change the sort order.
:::

## Example

`q = order q by 'count' desc;`

## Example

To `order` a stream by multiple fields, use this syntax:

```nolang
a = load "0Fbxx000000002qCAA/0Fcxx000000002WCAQ";
b = group a by (year, month);
c = foreach b generate year as year, month as month;
d = order c by (year desc, month desc);
```

## Example

You can order a cogrouped stream before a `foreach` statement:

```nolang
a = load "0Fbxx000000002qCAA/0Fcxx000000002WCAQ";
b = load "0Fayy000000002qCAA/0Fbyy000000002WCAQ";
c = cogroup a by year, b by year;
c = order c by a.airlineName;
c = foreach c generate year as year;
```

## Example

By default, nulls are sorted first when sorting in descending order. To change the null sort order to last, use this syntax:

```nolang
q = order q by last_shipping_cost desc nulls last;
```

## Example

You can’t reference a preprojection ID in a postprojection `order` operation. (Projection is another term for a `foreach` operation.) This code throws an error:

```nolang
q = load "0Fbxx000000002qCAA/0Fcxx000000002WCAQ";
q = group q by 'FirstName';
q = foreach q generate sum('mea_mm10M') as 'sum_mm10M';
q = order q by 'FirstName' desc;
```

This code is valid:

```nolang
q = load "0Fbxx000000002qCAA/0Fcxx000000002WCAQ";
q = group q by 'FirstName';
q = foreach q generate 'FirstName' as 'User_FirstName', sum('mea_mm10M') as 'sum_mm10M';
q = order q by 'User_FirstName' desc;
```

**See Also**

- [Statements](/docs/analytics/bi-dev-guide-saql/guide/bi-saql-statements.md)
