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.
Examples
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;
baseurl.'/images/orderby.jpg'; ?> alt="single column orderby">
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;
baseurl.'/images/multiplejoin.jpg'; ?> alt="multiple column orderby">
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;
baseurl.'/images/ascorderby.jpg'; ?> alt="asc orderby">
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;
baseurl.'/images/descorderby.jpg'; ?> alt="desc orderby">