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 FIRSTorNULLS LAST— Explicitly places missing values. By default,NULLprecedes other values in ascending order.COLLATE— Selects text comparison rules.BINARYuses the ordinary comparison;NOCASEfolds ASCII case andRTRIMignores 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",80Case-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"
\NSee LIMIT for selecting a bounded sorted result.