Sorting of SQL query results
Sort in ascending order:
When the order by clause is used, data is arranged in ascending order by default. Therefore, you can use the ASC keyword to indicate the ascending ORDER or not to specify it. The default value is ascending, the display effect is the same, for example:
Sort in descending order:
To sort query results in descending order, you must specify the DESC keyword after sorting. To view the descending order of employee salaries:
Common usage
Sort by unselected list:
You can also SELECT columns without sorting. For example:
Sort by expression:
An arithmetic expression can appear in a SELECT column. You can also use an expression to sort the results of expression calculation. For example:
Sort by column alias:
When performing a SELECT query, you can define aliases for columns or expressions. When performing sorting, you can use aliases for sorting. For example:
Sort by column position:
We can also sort by column or expression in the SELECT list, which can effectively reduce the length of the sort statement. In addition, if the column names in the SELECT list are different when UNION is used, the column position must be used for sorting. For example, the Department Code and staff code are used as the standard in ascending order.
Use multi-column sorting:
When performing an operation, you can also sort by multiple columns. When multiple columns are used as sorting criteria, they are first sorted by the first column. If the data in the first column is the same, they are sorted by the second column, and so on. For example: