How to use the ORDER BY sorting in MySQL?
In MySQL, the ORDER BY clause is used to sort the query results. It can sort in ascending or descending order based on one or more columns.
Basic grammar:
SELECT 列名 FROM 表名 ORDER BY 列名 [ASC|DESC];
- Column name: The name of the column to be sorted.
- Table name: the name of the table you want to query.
- ASC: Indicates sorting in ascending order (default).
- DESC: Indicates sorting in descending order.
Suppose there is a table called “students” with columns “id”, “name”, and “age”. We want to query the results in descending order by age.
SELECT * FROM students ORDER BY age DESC;
This will return a student list sorted in descending order by age.
To sort by multiple columns, you can specify the column names in the ORDER BY clause separated by commas.
SELECT * FROM students ORDER BY age DESC, name ASC;
This will be sorted initially in descending order by age, then in cases of the same age, it will be sorted in ascending order by name.
Please note that the ORDER BY clause is typically used in SELECT queries, but can also be used in UPDATE or DELETE queries to update or delete rows in a specific order.