ORDER BY
Function
The ORDER BY clause is used to perform global sorting on query results. Spark 4.0 enhances the sorting functionality by supporting NULLS FIRST/LAST to specify the sort position of NULL values and can be used with OFFSET for pagination.
Syntax
SELECT projectItem [, ...] FROM table_reference
ORDER BY { expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] } [, ...] Parameters
| Parameter | Description |
|---|---|
| expression | The sort expression. Can be a column name, column alias, or expression. |
| ASC | Sorts in ascending order. This is the default option. |
| DESC | Sorts in descending order. |
| NULLS FIRST | Places NULL values at the beginning of the sort result. |
| NULLS LAST | Places NULL values at the end of the sort result. By default, NULLs are placed last in ascending order and first in descending order. |
Precautions
- ORDER BY performs global sorting. All data is gathered into a single Reducer for processing.
- When used with GROUP BY, ORDER BY can be followed by aggregate functions.
- ORDER BY can reference aliases from the SELECT list.
- Can be used with LIMIT and OFFSET for pagination queries.
Examples
Sort by a single column in ascending order:
SELECT * FROM student ORDER BY score;
Sort by a single column in descending order:
SELECT * FROM student ORDER BY score DESC;
Sort by multiple columns:
SELECT * FROM student ORDER BY class_id ASC, score DESC;
Specify NULL value sort position:
SELECT * FROM student ORDER BY score DESC NULLS LAST;
Sort using a column alias:
SELECT name, score * 1.5 AS weighted_score FROM student ORDER BY weighted_score DESC;
Pagination query (with OFFSET, Spark 4.0):
SELECT * FROM student ORDER BY score DESC LIMIT 10 OFFSET 20;
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot