The ORDER BY clause in SQL is used to sort the result set. The syntax is: ORDER BY column_name [ASC | DESC]. It allows records to be sorted in ascending or descending order according to specified columns or expressions, and can accept multiple columns at the same time to achieve multi-level sorting. NULL sorting behavior can be specified with the IS NULL and COALESCE functions.
Using ORDER BY in SQL
In SQL, the ORDER BY clause is used to set the query results rows to sort. It allows us to sort records in ascending or descending order based on a specified column or expression.
Usage:
<code class="sql">SELECT column_list FROM table_name ORDER BY column_name [ASC | DESC];</code>
Parameters:
Example:
To sort the employees in the employees table by last_name in ascending order, we can use the following query:
<code class="sql">SELECT * FROM employees ORDER BY last_name ASC;</code>
This will Produces the following results:
<code class="text">| employee_id | first_name | last_name | |-------------|------------|------------| | 1 | John | Adams | | 2 | Jane | Doe | | 3 | Michael | Smith |</code>
Sort multiple columns:
The ORDER BY clause can accept multiple columns at the same time, thereby achieving multi-level sorting. The sort order of the columns will determine how the final results are sorted.
<code class="sql">SELECT * FROM employees ORDER BY last_name ASC, first_name DESC;</code>
This query will first sort by last_name in ascending order and then by first_name in descending order.
Sort NULL Values:
When using ORDER BY, NULL values will be treated as the minimum or maximum value, depending on the sort order. You can specify sorting behavior for null values by using the IS NULL and COALESCE functions.
Note:
The above is the detailed content of How to use order by in sql. For more information, please follow other related articles on the PHP Chinese website!