SQL multi-column sorting: flexible use of ascending and descending order
In SQL database operations, it is often necessary to sort multiple columns, not only for data organization, but more importantly to achieve specific sorting requirements. Suppose there is a table containing two columns, 'column1' and 'column2', and it is necessary to sort the 'column1' column in descending order while maintaining the 'column2' column in ascending order.
SQL's ORDER BY
clause provides a concise syntax to implement different sorting directions for multiple columns. Its syntax is as follows:
ORDER BY column1 DESC, column2
In this example, the DESC
keyword specifies the 'column1' column to be sorted in descending order, and the 'column2' column does not specify a sorting direction, so it defaults to ascending order (SQL's default sorting method).
This sorting strategy gives priority to the 'column1' column. Each record with a different 'column1' value will be arranged in the specified order. For records with the same 'column1' value, the query will be further sorted according to the ascending order of the 'column2' column.
For example, consider a table containing the following data:
column1 | column2 |
---|---|
10 | 5 |
30 | 20 |
20 | 15 |
20 | 10 |
Executing the following query against this table will produce the desired sorted results:
SELECT * FROM table ORDER BY column1 DESC, column2
The result will be:
column1 | column2 |
---|---|
30 | 20 |
20 | 10 |
20 | 15 |
10 | 5 |
The above is the detailed content of How to Sort Multiple SQL Columns with Different Ascending and Descending Orders?. For more information, please follow other related articles on the PHP Chinese website!