MySQL’s ORDER BY clause is used to sort query results by specified columns. It supports ascending (ASC) and descending (DESC) sorting and can sort multiple columns simultaneously. NULL values are usually treated as the smallest value, but they can be treated as the largest value using the COALESCE() function. The ORDER BY clause also allows sorting using expressions and can optimize sort performance by creating indexes, using covering indexes, and limiting the number of rows returned.
Usage of ORDER BY in MySQL
Use of ORDER BY clause
The ORDER BY clause is used to sort query results so that they are displayed in a specific order. It sorts data rows based on a specified expression or column.
Basic syntax:
<code class="sql">SELECT column_list FROM table_name ORDER BY column_name [ASC | DESC];</code>
Multiple sorting columns
Can sort multiple columns at the same time. Each sorting column is separated by commas and sorted by priority from left to right. For example:
<code class="sql">SELECT * FROM table_name ORDER BY last_name ASC, first_name DESC;</code>
This will sort first by last name in ascending order, then by first name in descending order if last names are equal.
Ordering of NULL values
NULL values are usually treated as the smallest value when sorting. To treat a NULL value as the largest value when sorting in descending order, you can use the COALESCE() function to replace it with a non-NULL value. For example:
<code class="sql">SELECT * FROM table_name ORDER BY COALESCE(salary, 0) DESC;</code>
Ordering using expressions
You can use expressions in the ORDER BY clause instead of column names. Expressions can include constants, functions, and operators. For example, sorting by age range:
<code class="sql">SELECT * FROM table_name ORDER BY CASE WHEN age < 18 THEN 'Minor' WHEN age >= 18 AND age < 65 THEN 'Adult' ELSE 'Senior' END;</code>
Optimize sort performance
When sorting large data sets, it is important to optimize sort performance. The following techniques can be used:
The above is the detailed content of How to use orderby in mysql. For more information, please follow other related articles on the PHP Chinese website!