MySQL Order By

MySQL order by data sorting is important where we want to display the data in any particular 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.

Syntax of ORDER BY

SELECT * FROM table_name ORDER BY 'field_name(s)'




MySQL Order By Exercise

1. Write a MySQL statement to select data of all departments in descending order by age.

Suppose the table is -

 +----+--------------+------------+-----+
| id | name         | department | age |
+----+--------------+------------+-----+
|  1 | Maria Gloria | CS         |  22 |
|  2 | John Smith   | IT         |  23 |
|  3 | Gal Rao      | CS         |  22 |
|  4 | Jakey Smith  | EC         |  24 |
|  5 | Rama Saho    | IT         |  22 |
|  6 | Maria Gaga   | EC         |  23 |
+----+--------------+------------+-----+

Solution

The default sort order is ascending, with smallest values first. To sort the data in descending order, add the DESC keyword to the name of the column you are sorting by -

The following statement returns student data of all departments in descending order by age.

 mysql> SELECT * FROM students
     -> ORDER BY age DESC;

Output of the above statement -

+----+--------------+------------+-----+
| id | name         | department | age |
+----+--------------+------------+-----+
|  4 | Jakey Smith  | EC         |  24 |
|  2 | John Smith   | IT         |  23 |
|  6 | Maria Gaga   | EC         |  23 |
|  1 | Maria Gloria | CS         |  22 |
|  3 | Gal Rao      | CS         |  22 |
|  5 | Rama Saho    | IT         |  22 |
+----+--------------+------------+-----+

2. Write a MySQL statement to select data of all departments in ascending order by name and age.

Solution

The following statement returns student data of all departments in ascending order by name and age.

 mysql> SELECT * FROM students
     -> ORDER BY 'name', 'age';




Related MySQL Exercises

MySQL concatenate
MySQL Get Current Date, User, Version
MySQL Get Maximum Value
MySQL Administrator
MySQL where clause
MySQL get difference between two dates
MySQL Pattern Matching
MySQL Join
MySQL Regular Expression
MySQL delete duplicate row
MySQL update multiple rows
Get nth highest salary using MySQL
Display the nth row from MySQL
Commit and rollback in mysql
MySQL SELECT top 5
MySQL display the alternate rows




Read more articles


General Knowledge



Learn Popular Language