The OrderBy clause is used to sort SQL query results by the specified column. Syntax: SELECT ... ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ... Parameters: 1. Column to be sorted 2. Optional sort order: [ASC (ascending) | DESC (descending) )]
Usage of OrderBy in SQL
The OrderBy clause is used to match the SQL query results according to the specified column to sort.
Syntax:
##SELECT ... ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...
Parameters:
,
column2, ...: the column to be sorted
: Sort in ascending order (from small to large)
: Sort in descending order (from large to small)
Usage:
<code class="sql">SELECT name, age FROM customers ORDER BY name ASC;</code>
<code class="sql">SELECT name, age, city FROM customers ORDER BY name ASC, age DESC;</code>
<code class="sql">SELECT name, age FROM customers ORDER BY age DESC;</code>
COALESCE() function, for example:
<code class="sql">SELECT name, age FROM customers ORDER BY COALESCE(age, 0) ASC;</code>This will sort by age in ascending order, treating NULL values as 0.
<code class="sql">SELECT name, city, state FROM customers ORDER BY name ASC, city DESC;</code>This will sort each state first Sort by name in ascending order and then by city in descending order.
The above is the detailed content of How to use orderby in sql. For more information, please follow other related articles on the PHP Chinese website!