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 MySQL table. For displaying data in some meaningful way ORDER BY clause is used.

This sorts your result on the basis of 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 with multiple columns
  4. Conclusion

 

1. Data Source

I am using emp_salary table for demonstration which 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 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 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 with 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 above query, I am ordering salary table by 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 use with the SELECT query to arrange result in specific order. You just need to separate your column names by the comma(,) when you are specifying multiple columns.

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *