

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- Order by a function of two columns in a single MySQL query
- How to order by the highest value from two columns in MySQL?
- Display two different columns from two different tables with ORDER BY?
- How to order MySQL rows by multiple columns?
- Split float value in two columns of a MySQL table?
- Order by multiple columns not working as expected in MySQL?
- MySQL query to order by two fields and NULL values in chronological order?
- How to update a MySQL table by swapping two column values?
- Return order of MySQL SHOW COLUMNS?
- Select and add result of multiplying two columns from a table in MySQL?
- MongoDB order by two fields sum?
- ORDER BY a specific word in MySQL
- MySQL Order By specific strings?
- MySQL Order by with case?
- MySQL Order by beginning letter?
Advertisements