SORT BY 子句
適用于: Databricks SQL Databricks Runtime
傳回依使用者指定順序排序之每個資料分割內的結果資料列。 當有多個分割 SORT BY
區可能會傳回部分排序的結果。 這與 ORDER BY 子句不同,可保證輸出的總順序。
語法
SORT BY { expression [ sort_direction nulls_sort_oder ] } [, ...]
sort_direction
[ ASC | DEC ]
nulls_sort_order
[ NULLS FIRST | NULLS LAST ]
參數
-
用來建立傳回結果之資料分割區域順序之任何類型的運算式。
如果運算式是常值 INT 值,則會解譯為選取清單中的資料行位置。
sort_direction
指定依運算式排序的排序次序。
ASC
:此運算式的排序方向為遞增。DESC
:此運算式的排序次序遞減。
如果未明確指定排序方向,則預設會以遞增方式排序資料列。
nulls_sort_order
選擇性地指定是否在非 Null 值之前/之後傳回 Null 值。 如果未
null_sort_order
指定 ,則如果排序次序為 ,則 Null 會先排序,如果排序次序為ASC
DESC
,則為最後一個 NullS 排序。NULLS FIRST
:不論排序次序為何,都會先傳回 Null 值。NULLS LAST
:不論排序次序為何,都會最後傳回 Null 值。
指定多個運算式排序時,會由左至右進行。 分割區內的所有資料列都會依第一個運算式排序。 如果第一個運算式有重複的值,則會使用第二個運算式來解析重複專案群組內的順序等等。 產生的順序,如果運算式在所有順序中都有重複的值,則結果順序不具決定性。
例子
> CREATE TEMP VIEW person (zip_code, name, age)
AS VALUES (94588, 'Zen Hui', 50),
(94588, 'Dan Li', 18),
(94588, 'Anil K', 27),
(94588, 'John V', NULL),
(94511, 'David K', 42),
(94511, 'Aryan B.', 18),
(94511, 'Lalit B.', NULL);
-- Use `REPARTITION` hint to partition the data by `zip_code` to
-- examine the `SORT BY` behavior. This is used in rest of the
-- examples.
-- Sort rows by `name` within each partition in ascending manner
> SELECT /*+ REPARTITION(zip_code) */ name, age, zip_code FROM person
SORT BY name;
Anil K 27 94588
Dan Li 18 94588
John V NULL 94588
Zen Hui 50 94588
Aryan B. 18 94511
David K 42 94511
Lalit B. NULL 94511
-- Sort rows within each partition using column position.
> SELECT /*+ REPARTITION(zip_code) */ name, age, zip_code FROM person
SORT BY 1;
Anil K 27 94588
Dan Li 18 94588
John V null 94588
Zen Hui 50 94588
Aryan B. 18 94511
David K 42 94511
Lalit B. null 94511
-- Sort rows within partition in ascending manner keeping null values to be last.
> SELECT /*+ REPARTITION(zip_code) */ age, name, zip_code FROM person
SORT BY age NULLS LAST;
18 Dan Li 94588
27 Anil K 94588
50 Zen Hui 94588
NULL John V 94588
18 Aryan B. 94511
42 David K 94511
NULL Lalit B. 94511
-- Sort rows by age within each partition in descending manner, which defaults to NULL LAST.
> SELECT /*+ REPARTITION(zip_code) */ age, name, zip_code FROM person
SORT BY age DESC;
50 Zen Hui 94588
27 Anil K 94588
18 Dan Li 94588
NULL John V 94588
42 David K 94511
18 Aryan B. 94511
NULL Lalit B. 94511
-- Sort rows by age within each partition in descending manner keeping null values to be first.
> SELECT /*+ REPARTITION(zip_code) */ age, name, zip_code FROM person
SORT BY age DESC NULLS FIRST;
NULL John V 94588
50 Zen Hui 94588
27 Anil K 94588
18 Dan Li 94588
NULL Lalit B. 94511
42 David K 94511
18 Aryan B. 94511
-- Sort rows within each partition based on more than one column with each column having
-- different sort direction.
> SELECT /*+ REPARTITION(zip_code) */ name, age, zip_code FROM person
SORT BY name ASC, age DESC;
Anil K 27 94588
Dan Li 18 94588
John V null 94588
Zen Hui 50 94588
Aryan B. 18 94511
David K 42 94511
Lalit B. null 94511