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>
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>
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!