Introduction
We often need the records in the table to be sorted in some order. If the records are arranged in increasing order of some column, then it is called ascending order, and if the records are arranged in decreasing order of some column, then it is called descending order. For getting the sorted records in the table, we use the ORDER BY command. By default, the ORDER BY keyword sorts the records in ascending order.
Recommended topics, Coalesce in SQL and Tcl Commands in SQL
Ordering according to only one column:
Syntax:
SELECT col1,col2,..coln FROM table_name [WHERE condition] [ORDER BY col1, col2, .. coln] [ASC | DESC]; |
Here
SELECT col1,...coln FROM `table_name` is the command that tells the MySQL server to select the col1,..coln from `table_name.`
(column_1,column_2,…) specifies the columns to select from.
Here ASC is for ascending order display, and DESC is for descending order display.
Example
Consider the following student’s records table. What will be the SQL query command if we wish to display the table by ascending order (increasing order) of roll no.?
Roll_No | Marks | Name | Address | City |
3 | 87 | AAA | M.G. road | Pune |
1 | 87 | DDD | Chandani chowk | Delhi |
2 | 63 | GGG | Viman Nagar | Mumbai |
4 | 55 | HHH | Kuber Nagar | Ahmedabad |
The query for the above question will be as follows:
SELECT * FROM students_details ORDER BY Roll_No ASC; |
The above query will result in the following output.
Roll_No | Marks | Name | Address | City |
1 | 87 | DDD | Chandani chowk | Delhi |
2 | 63 | GGG | Viman Nagar | Mumbai |
3 | 87 | AAA | M.G. road | Pune |
4 | 55 | HHH | Kuber Nagar | Ahmedabad |
In the same example, if we want to sort in descending order, we have to use DESC in place of ASC.
SELECT * FROM students_details ORDER BY Roll_No DESC; |
The above query will result in the following output.
Roll_No |
Marks |
Name |
Address |
City |
4 |
55 |
HHH |
Kuber Nagar |
Ahmedabad |
3 |
87 |
AAA |
M.G. road |
Pune |
2 |
63 |
GGG |
Viman Nagar |
Mumbai |
1 |
87 |
DDD |
Chandani chowk |
Delhi |