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

How to Sort SQL Results by Multiple Columns in Ascending and Descending Order?

Mary-Kate Olsen
Release: 2025-01-21 21:11:13
Original
869 people have browsed it

How to Sort SQL Results by Multiple Columns in Ascending and Descending Order?

Mastering Multi-Column Sorting in SQL: Ascending and Descending

SQL's ORDER BY clause is your key to organizing tabular data. But what if you need to sort by multiple columns, each in a different direction (ascending or descending)? This guide shows you how.

Sorting Columns in Opposite Directions

The secret lies in combining ORDER BY with the DESC (descending) and ASC (ascending) keywords. The syntax is straightforward:

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

This query sorts results descendingly by column1, and then, within each column1 group, ascendingly by column2.

Illustrative Example

Imagine this table:

Column1 Column2
A 10
B 5
C 15
D 5
E 20

To sort it descendingly by Column1 and then ascendingly by Column2, use this query:

<code class="language-sql">SELECT * FROM table ORDER BY Column1 DESC, Column2 ASC;</code>
Copy after login

The output would be:

Column1 Column2
E 20
C 15
B 5
D 5
A 10

Notice the two-stage sorting: Column1 is sorted descending (E, C, B, D, A), and then ties in Column1 are broken by ascending Column2 (20, 15, 5, 5, 10). This layered approach provides precise control over your result ordering.

The above is the detailed content of How to Sort SQL Results by Multiple Columns in Ascending and Descending Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template