How to use Order by with Multiple columns in MySQL

The data is not displayed in any particular order when you simply fetch it from the MySQL table. For displaying data in some meaningful way ORDER BY clause is used.

This sorts your result on the basis of the column name specified in the clause within the SELECT query.

It allows us to –

  • Specify ordering in single or multiple columns
  • Define sort results in ASC or DESC format.

How to use Order by with Multiple columns in MySQL


Contents

  1. Data Source
  2. Order by
  3. Using Order by multiple columns
  4. Conclusion

1. Data Source

I am using emp_salary table in the example that has the following data –

id username age salary
1 yssyogesh 23 24000
2 sonarika 23 32000
3 akilesh 25 28000
4 anil 24 21000
5 ajay 21 22000
6 vijay 24 23000
7 sunil 23 22000

 


2. Order by

This sorts your MySQL table result in Ascending or Descending order according to the specified column. The default sorting order is Ascending which you can change by using ASC or DESC.

Syntax –

SELECT * FROM [table-name] 
ORDER BY 
[column-name1 ] [ASC|DESC] ,  
[column-name2] [ASC|DESC],..

Example

SELECT * FROM emp_salary ORDER BY age

Or

SELECT * FROM emp_salary ORDER BY age asc

Here, I am arranging the result by age column and sorting it in ascending.

Output

id username age salary
5 ajay 21 22000
1 yssyogesh 23 24000
2 sonarika 23 32000
7 sunil 23 22000
4 anil 24 21000
6 vijay 24 23000
3 akilesh 25 28000

 


3. Using Order by multiple columns

Define your multiple column names in ORDER BY clause separated by a comma (,). You can also specify your sorting order ASC or DESC.

Example

SELECT * FROM emp_salary ORDER BY age ASC, salary DESC

In the above query, I am using order by in two columns –  age in ascending order and salary by descending order.

Output

id username age salary
5 ajay 21 22000
2 sonarika 23 32000
1 yssyogesh 23 24000
7 sunil 23 22000
6 vijay 24 23000
4 anil 24 21000
3 akilesh 25 28000

 


4. Conclusion

Order by clause is used with the SELECT query to arrange results in a specific order. You just need to separate your column names by the comma(,) when you are specifying multiple columns.

If you found this tutorial helpful then don't forget to share.

Leave a Comment