The ORDER BY clause in SQL is used to arrange query results in a specific order. It uses the following syntax: ORDER BY column_name [ASC | DESC] [, ...], where ASC means ascending order and DESC means descending order. This clause can also sort by multiple columns, with priority determined by the order of the columns. By default, NULL values are ranked lowest, but this behavior can be modified with the NULLS FIRST or NULLS LAST clause.
ORDER BY clause in SQL
ORDER BY clause is used to sort the retrieved data. The results are arranged in a specific order.
Syntax:
<code class="sql">ORDER BY column_name [ASC | DESC] [, column_name [ASC | DESC]] ...</code>
Meaning:
column_name
: Specify the column to be sorted Column name. ASC
: Sort in ascending order (from small to large). DESC
: Sort in descending order (from large to small). Example:
<code class="sql">SELECT * FROM customers ORDER BY last_name ASC;</code>
This will sort the customer data by last name from smallest to largest.
Multiple column sorting:
The ORDER BY clause can sort by multiple columns. The order of the columns specifies the priority of the sort, with the first column having the highest priority.
Example:
<code class="sql">SELECT * FROM customers ORDER BY last_name ASC, first_name DESC;</code>
This will sort the customer data by last name from smallest to largest, and by first name from largest to smallest if the last name is the same.
NULL value handling:
By default, NULL values are treated as the smallest value in sorting. This behavior can be modified using the NULLS FIRST
or NULLS LAST
clause.
NULLS FIRST
: Sort NULL values first. NULLS LAST
: Sort NULL values last. Example:
<code class="sql">SELECT * FROM customers ORDER BY last_name ASC NULLS LAST;</code>
This will sort the customer data by last name from smallest to largest, placing NULL values last.
Note:
SELECT
statement. The above is the detailed content of What does order by mean in sql. For more information, please follow other related articles on the PHP Chinese website!