Sort results

You might have noticed that, when you use the SELECT statement to query data, the results are not sorted in any orders. To sort returned results by one or more columns in ascending or descending order, you can use the ORDER BY clause. Here is the syntax:

SELECT column1, column2,... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...

Here is a simple example. We will work with the following table:

mysql> SELECT * FROM testtb;
 +-------+-------------+------+
 | name | surname | year |
 +-------+-------------+------+
 | Amy | Bryant | 1991 |
 | Mark | Smith | 1955 |
 | John | von Neumann | 1921 |
 | Aaron | Rogers | 1995 |
 | Brian | Cormier | 1988 |
 +-------+-------------+------+
 5 rows in set (0.00 sec)

To sort the results by name, we would use the following command:

mysql> SELECT * FROM testtb ORDER BY name;
 +-------+-------------+------+
 | name | surname | year |
 +-------+-------------+------+
 | Aaron | Rogers | 1995 |
 | Amy | Bryant | 1991 |
 | Brian | Cormier | 1988 |
 | John | von Neumann | 1921 |
 | Mark | Smith | 1955 |
 +-------+-------------+------+
 5 rows in set (0.01 sec)

To sort in descending order, we would add the DESC keyword after the column name:

mysql> SELECT * FROM testtb ORDER BY name DESC;
 +-------+-------------+------+
 | name | surname | year |
 +-------+-------------+------+
 | Mark | Smith | 1955 |
 | John | von Neumann | 1921 |
 | Brian | Cormier | 1988 |
 | Amy | Bryant | 1991 |
 | Aaron | Rogers | 1995 |
 +-------+-------------+------+
 5 rows in set (0.00 sec)
Geek University 2022