Home >Database >Mysql Tutorial >How to Order Multiple Columns with Different Sort Directions in SQL?
Multi-Column Sorting in SQL with Varying Directions
SQL often requires sorting data across multiple columns, sometimes using different sort orders for each. The ORDER BY
clause handles this.
To sort by multiple columns with distinct ascending/descending directions, use this structure:
<code class="language-sql">ORDER BY column1 DESC, column2 ASC</code>
Here, column1
is sorted descending (DESC
), and column2
is sorted ascending (ASC
- the default). The database first orders by column1
descendingly. Then, for rows with identical column1
values, it sorts them by column2
ascendingly.
This layered sorting is useful when you need a primary sorting column, but also require further ordering within groups sharing the same primary column value.
The above is the detailed content of How to Order Multiple Columns with Different Sort Directions in SQL?. For more information, please follow other related articles on the PHP Chinese website!