ORDER BY

constructsupportedQueries & DML

docs.snowflake.com ↗

Specifies an ordering of the rows of the result table from a SELECT list.

Syntax

supportedpartialnot supportednot scored

Sorting by specific columns

SELECT ...
  FROM ...
  ORDER BY orderItem [ , orderItem , ... ]
  [ ... ]

Where

orderItem ::= { <column_alias> | <position> | <expr> } [ { ASC | DESC } ] [ NULLS { FIRST | LAST } ]

Sorting by all columns

SELECT ...
  FROM ...
  ORDER BY ALL [ { ASC | DESC } ] [ NULLS { FIRST | LAST } ]
  [ ... ]

Parameters

NameRequiredDescription
column_aliasColumn alias appearing in the query block’s SELECT list.
positionPosition of an expression in the SELECT list.
exprAny expression on tables in the current scope.
{ ASC | DESC }Optionally returns the values of the sort key in ascending (lowest to highest) or descending (highest to lowest) order. Default: ASC
NULLS { FIRST | LAST }Optionally specifies whether NULL values are returned before/after non-NULL values, based on the sort order (ASC or DESC). Default: Depends on the sort order (ASC or DESC); see the usage notes below for details
ALLSorts the results by all of the columns specified in the SELECT list. The results are sorted by the columns in the order in which they appear. For example, suppose that the SELECT list contains:Copy code SELECT col_1, col_2, col_3 FROM my_table ORDER BY ALL; The results are sorted first by col_1, then by col_2, and then by col_3. Note You cannot specify ORDER BY ALL if a column in the SELECT list uses an aggregate function.

Usage notes

Parameters

column_alias: Column alias appearing in the query block’s SELECT list. position: Position of an expression in the SELECT list. expr: Any expression on tables in the current scope. { ASC | DESC }: Optionally returns the values of the sort key in ascending (lowest to highest) or descending (highest to lowest) order. Default: ASC NULLS { FIRST | LAST }: Optionally specifies whether NULL values are returned before/after non-NULL values, based on the sort order (ASC or DESC). Default: Depends on the sort order (ASC or DESC); see the usage notes below for details ALL: Sorts the results by all of the columns specified in the SELECT list. The results are sorted by the columns in the order in which they appear. For example, suppose that the SELECT list contains:Copy code SELECT col_1, col_2, col_3 FROM my_table ORDER BY ALL; The results are sorted first by col_1, then by col_2, and then by col_3. Note You cannot specify ORDER BY ALL if a column in the SELECT list uses an aggregate function.