# ORDER BY

`ORDER BY` sorts the query result by one or more expressions. The first expression is compared first; later expressions break ties.

Without `ORDER BY`, result order is unspecified. Use a unique tie breaker when `LIMIT` or `OFFSET` must return a repeatable page.

## Syntax

```text
ORDER BY expression [COLLATE collation] [ASC | DESC]
         [NULLS FIRST | NULLS LAST] [, ...]
```

* `ASC` — Ascending order; the default.
* `DESC` — Descending order.
* `NULLS FIRST` or `NULLS LAST` — Explicitly places missing values. By default, `NULL` precedes other values in ascending order.
* `COLLATE` — Selects text comparison rules. `BINARY` uses the ordinary comparison; `NOCASE` folds ASCII case and `RTRIM` ignores trailing spaces.

Ordering can use a result alias or a result-column position. An `ORDER BY` inside `OVER` defines a window's calculation order and does not replace the outer ordering.

## Examples

### Sorting by total and then name

```sql
CREATE TABLE accounts (name TEXT, total INTEGER);
INSERT INTO accounts VALUES ('Grace', 100), ('Ada', 100), ('Sam', 80);
```

```sql
SELECT name, total
FROM accounts
ORDER BY total DESC, name ASC
FORMAT csv;
```

```text
"Ada",100
"Grace",100
"Sam",80
```

### Case-insensitive text and NULL placement

```sql
CREATE TABLE labels (value TEXT);
INSERT INTO labels VALUES ('b'), ('A'), (NULL);
```

```sql
SELECT value
FROM labels
ORDER BY value COLLATE NOCASE NULLS LAST
FORMAT csv;
```

```text
"A"
"b"
\N
```

See [`LIMIT`](https://coordinatordb.com/docs/reference/statements/select/limit) for selecting a bounded sorted result.
