Home >Database >Mysql Tutorial >How to Order Multiple Columns with Different Sort Directions in SQL?

How to Order Multiple Columns with Different Sort Directions in SQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 21:06:15522browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn