Sorting, ORDER BY operator
When executing a SELECT query, the rows are returned by default in an undefined order. In fact, the order of rows in this case depends on the connection and scanning plan, as well as the order of data placement on the disk, so it cannot be relied upon. The ORDER BY construct is used to order the records.
General query structure with ORDER BY operator
SELECT table_fields FROM table_name
[WHERE condition]
ORDER BY column [ASC | DESC] [, ...];- [ ]optional part
- a | bone of the options
- ...can be repeated
- table_fields
- The columns to include in the result.
- table_name
- The table to select data from.
- condition
Which rows to keep before sorting.
Optional- column
The column whose values define the order of rows. You can list several columns separated by commas.
- ASC | DESC
Sorting direction: ASC for ascending (the default), DESC for descending.
KeywordOptionalASCDESC
For example, let's display the names of airlines in alphabetical order from the Company table:
MySQL 8.4SELECT name FROM Company ORDER BY name;
Sorting in ascending and descending order for main types
Sorting by multiple columns
To sort results by two or more columns, they should be specified separated by commas.
ORDER BY column_1 [ASC | DESC], column_2 [ASC | DESC];- [ ]optional part
- a | bone of the options
- column_1
- The column rows are sorted by first.
- column_2
The column used to sort rows that have the same value in column_1.
- ASC | DESC
Sorting direction for the column it follows. The default is ASC.
KeywordOptionalASCDESC
Data will be sorted by the first column, but in case there are multiple records with identical values in the first column, they will be sorted by the second column. The number of columns that can be sorted is unlimited.
Let's display flight information sorted by the departure city in ascending order and by the arrival city in descending order, from the Trip table:
MySQL 8.4SELECT DISTINCT town_from, town_to FROM Trip ORDER BY town_from, town_to DESC;
In this example, the entries are sorted by the town_from field first. Then, it performs reverse sorting by the town_to field for groups of rows that have the same value in the town_from column.