View a markdown version of this page

ORDER BY clause - Amazon Athena

ORDER BY clause

The ORDER BY clause sorts the result by one or more expressions, from left to right. ASC, the default, sorts from the smallest value to the largest, and DESC from the largest to the smallest. You can sort by a column, an expression, an alias of the select list, or the position of a select list item.

By default, NULL values sort last, in both ascending and descending order. To choose where they go, add NULLS FIRST or NULLS LAST.

ORDER BY ALL sorts by every column of the result, from left to right. Add DESC to sort every column in descending order.

Syntax

ORDER BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ORDER BY ALL [ ASC | DESC ] [ NULLS { FIRST | LAST } ]

Examples

For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.

The following SQL query sorts the orders in the east region by amount, largest first. The NULL amount sorts last.

SELECT customer, amount FROM sales_db.sales_parquet WHERE region = 'east' ORDER BY amount DESC

The query returns the following results.

customer amount

alice

120.50

carol

42.25

frank

NULL

The following SQL query sorts the same orders by amount, smallest first, with the NULL amount first.

SELECT customer, amount FROM sales_db.sales_parquet WHERE region = 'east' ORDER BY amount NULLS FIRST

The query returns the following results.

customer amount

frank

NULL

carol

42.25

alice

120.50

The following SQL query sorts by every column of the result: first by region, then by customer.

SELECT region, customer FROM sales_db.sales_parquet ORDER BY ALL

The query returns the following results.

region customer

east

alice

east

carol

east

frank

north

dave

west

bob

west

erin

Considerations

Only the ORDER BY clause of the outermost query fixes the order of the result. An ORDER BY in a subquery or a common table expression does not.