How to sort more than one column at a time in MySQL?


To sort more than one column at a time, you can use ORDER BY clause. Following is the syntax −

select yourColumnName1,yourColumnName2,yourColumnName3 from yourTableName
order by yourColumnName2,yourColumnName3;

Let us first create a table −

mysql> create table doubleSortDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentCountryName varchar(10)
   -> );
Query OK, 0 rows affected (0.71 sec)

Following is the query to insert records in the table using insert command −

mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('John','AUS');
Query OK, 1 row affected (0.21 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Sam','UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Bob','US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Carol','UK');
Query OK, 1 row affected (0.32 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('David','AUS');
Query OK, 1 row affected (0.19 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Larry','UK');
Query OK, 1 row affected (0.15 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from doubleSortDemo;

This will produce the following output −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | John        | AUS                |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
| 4         | Carol       | UK                 |
| 5         | David       | AUS                |
| 6         | Larry       | UK                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

Following is the query to perform MySQL sort on more than one column i.e. Student country and name −

mysql> select StudentId,StudentName,StudentCountryName from doubleSortDemo
   -> order by StudentCountryName,StudentName;

This will produce the following output −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 5         | David       | AUS                |
| 1         | John        | AUS                |
| 4         | Carol       | UK                 |
| 6         | Larry       | UK                 |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements