ORDER BY in MySQL


ORDER BY 

In MySQL, an Order By is used to sort the data in a record set. Use multiple sorting criteria separated by commas. By default the Order By keyword sort the records in ascending order.

ORDER BY will tell the MySQL server to sort the rows by a column. Define in which direction to sort, as the order of the returned rows may not yet be meaningful. Rows can be returned in ascending or descending order.

Then you query your MySQL database, you can sort the results by any field in an ascending or descending order by just adding 'ORDER BY' at the end of your query. You would use ORDER BY field_name ASC for an ascending sort, or ORDER BY field_name DESC for a descending sort.  

Order by sorts by multiple columns, as sometimes I'll come across large groups rows that were sorted on the same number.

For Example : For the given example use a table 'emp_information' with the given fields.

img-1.gif

Use ASC : Using ASC will sort the data so that you see the smallest number first.

Example: In the given example we have to use emp_information table and sort the table in ascending order on the behalf of birth_date.

img-2.gif

Use DESC : Using DESC will sort the data so that you see the largest number first.

Example: For the given table sort in the descending order.

img-3.gif

ORDER BY using specific order from IN: We find the fields on the basics of specific emp_id field.

For Example :
SELECT * FROM emp_information WHERE emp_id IN (1,10,8,5) ORDER BY FIND_IN_SET(emp_id , '1,10,8,5');

img-5.gif

Up Next
    Ebook Download
    View all
    Learn
    View all