Sort a MySQL table by two columns with the help of the following 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)
With the help of The insert command inserts records into the table. 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 sort the two columns in the MySQL table. The query is as follows -
mysql> select *from OrderByDemo order by StudentId ASC, StudentAge ASC;
The following is the output of sorting the 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 it 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 - Primary sorting works first.
The above is the detailed content of Sort MySQL table by two columns?. For more information, please follow other related articles on the PHP Chinese website!