Home >Database >Mysql Tutorial >How to Order Multiple SQL Columns in Ascending and Descending Directions?

How to Order Multiple SQL Columns in Ascending and Descending Directions?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 20:51:10223browse

How to Order Multiple SQL Columns in Ascending and Descending Directions?

SQL multi-column sorting: combination of ascending and descending order

SQL uses the ORDER BY clause to sort query results by multiple columns. To sort multiple columns in different directions (ascending or descending), simply specify the desired direction after each column name.

For example, if you want to sort the query results by column1 in descending order and then by column2 in ascending order, you can use the following syntax:

<code class="language-sql">ORDER BY column1 DESC, column2</code>

Here’s how it works:

    The
  • keyword in column1 DESCDESC indicates that this column results should be sorted in descending order (highest value first).
  • There is no
  • or column2 after DESCASC, indicating that this column is sorted in ascending order (lowest value first).
  • The
  • columns are sorted in the order in which they appear in the ORDER BY clause, so column1 takes precedence over column2 sorting.

With this syntax, you can efficiently sort query results based on multiple criteria and different directions. This is useful in situations where you need to prioritize one column and provide a secondary sort level for another column.

The above is the detailed content of How to Order Multiple SQL Columns in Ascending and Descending Directions?. 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