MySQL Order By
Data sorting is important where we want to display the data in any particular order.
In previous articles, you have noticed that data displayed in no any order. MySQL provides ORDER BY clause to display data in an ordered way. The result set can be sorted in either ascending or descending order, by default it sort the data in ascending order and we can also sort by either single or multiple columns.
MySQL Order By Single Column
In this example, we have sorted the result set by single column 'first_name'.
mysql>SELECT * FROM students ORDER BY first_name;
MySQL Order By Multiple Columns
In this example, we have sorted the result set by multiple columns 'first_name' and 'last_name'.
mysql>SELECT S.*, B.book_id, B.issue_date FROM students S JOIN books B ON S.id = B.student_id ORDER BY B.book_id, S.class;
MySQL Ascending Order
In MySQL, the data is sorted by default in ascending order. The 'ASC' keyword is used to sort data in ascending order.
mysql>SELECT * FROM students ORDER BY last_name ASC;
MySQL Descending Order
To sort data in descending order, use DESC keyword. The given example returns the result set in descending order of 'last_name'.
mysql>SELECT * FROM students ORDER BY last_name DESC;