MySQL Tutorial
The MySQL ORDER BY clause is used to sort the data in ascending or descending order.
The basic syntax of the ORDER BY clause which would be used to sort the result in an ascending or descending order is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
Let's put these statements into real use.
We've a table named Students in our database that contains the following records:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | JAVA |
2 | SAM | Python |
3 | Sara | HTML | 4 | Rim | Java |
5 | Micheal | SQL |
6 | Lara | JAVA |
We will use 'ASE' keyword to ascending sort.
SELECT * FROM Students
ORDER BY NAME ASC;
The above SELECT statement selects all from Students table and sorted low to High by their NAME:
ROLL_NO | NAME | SUBJECT |
---|---|---|
6 | Lara | JAVA |
5 | Micheal | SQL |
4 | Rim | Java |
3 | Sara | HTML |
2 | SAM | Python |
1 | Will | JAVA |
Now we will fetch records from the Students table with Descending order.
We will use 'DESC' keyword to ascending sort.
SELECT * FROM Students
ORDER BY NAME DESC;
The above SELECT statement selects all from Students table and sorted High to low by thier NAME:
ROLL_NO | NAME | SUBJECT |
---|---|---|
1 | Will | JAVA |
2 | SAM | Python |
3 | Sara | HTML |
4 | Rim | Java |
5 | Micheal | SQL |
6 | Lara | JAVA |
WE can also Sort Students table using their ROLL_NO,SUBJECT.