22 Votes

MySQL: Order by multiple Columns

Question by Guest | Last update on 2021-07-02 | Created on 2015-02-05

I have made MySQL to sort my data coming from the database ascending or descending by using "ORDER BY col ASC" or "ORDER BY col DESC".

However, now, I would like to include two or more columns into my sorting. That is, in case there is the same value in the first column, the values should be sorted by the second column and so on.

Currently, for me, it is only possible to sort by the first column while in the second column, the values are disordered and totally messed up. Is there any possibility to realize this somehow?

ReplyPositiveNegative
2Best Answer2 Votes

You can write an arbitrary number of columns separated by a comma after your ORDER BY.

For example, you can use the following query to sort first by col1 followed by col2 and col3:

SELECT * FROM tab ORDER BY col1, col2, col3

You can also use ASC and DESC with this. If you do not write it out, ASC is taken by default.

SELECT * FROM tab ORDER BY col1 ASC, col2 DESC

This example, would sort ascending by col1 and after that descending by col2 (within same values in col1).
Last update on 2021-07-02 | Created on 2015-02-06

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.