Order a MySQL table by two columns?


Order a MySQL table by two columns with the help of below syntax −

order by yourColumnName1 DESC,yourColumnName2 DESC;

Let us first create a table for our example −

mysql> create table OrderByDemo
   -> (
   -> StudentId int,
   -> StudentName varchar(100),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (0.57 sec)

Inserting records into the table with the help of insert command. The query is as follows −

mysql> insert into OrderByDemo values(1,'John',23);
Query OK, 1 row affected (0.20 sec)
mysql> insert into OrderByDemo values(3,'Johnson',24);
Query OK, 1 row affected (0.27 sec)
mysql> insert into OrderByDemo values(4,'Carol',26);
Query OK, 1 row affected (0.14 sec)
mysql> insert into OrderByDemo values(2,'David',20);
Query OK, 1 row affected (0.13 sec)

Now, apply the above syntax to order by two columns in MySQL table. The query is as follows −

mysql> select *from OrderByDemo order by StudentId ASC, StudentAge ASC;

The following is the output that orders two columns in ascending order −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | John        |         23 |
|         2 | David       |         20 |
|         3 | Johnson     |         24 |
|         4 | Carol       |         26 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

Or you can do in descending order with the help of DESC command. The query is as follows −

mysql> select *from OrderByDemo order by StudentId DESC,StudentAge DESC;

The following is the output −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         4 | Carol       |         26 |
|         3 | Johnson     |         24 |
|         2 | David       |         20 |
|         1 | John        |         23 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

Note − The primary sort works first.

Updated on: 30-Jul-2019

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements