SQL ORDER BY Keyword
In SQL, the ORDER BY keyword is used to sort the resultant records in ascending or descending order.We use the ASC keyword to sort records in ascending order and we use DESC to sort records in descending order. By default the keyword sort the records in ascending order.
ORDER BY Syntax :
The syntax of the ORDER BY Keyword is −
SELECT column1, column2, ... columnN FROM table-name ORDER BY column1, column2, ... columnN ASC|DESC;
ORDER BY Keyword Example :
Consider the Customer table with the following records -
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
1 | Aarav | 28 | Udaipur | 28000 |
2 | Vivaan | 25 | Mumbai | 30000 |
3 | Reyansh | 28 | Chennai | 35000 |
4 | Muhammad | 24 | Udaipur | 50000 |
5 | Sai | 30 | Mumbai | 27000 |
TEST CASE 1 :- The following code is an example, which would fetch the all record from Customer table and sorted by the "Address" column.
SELECT * FROM Customer ORDER BY Address;
The result for the respective sql query is as follows −
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
3 | Reyansh | 28 | Chennai | 35000 |
2 | Vivaan | 25 | Mumbai | 30000 |
5 | Sai | 30 | Mumbai | 27000 |
1 | Aarav | 28 | Udaipur | 28000 |
4 | Muhammad | 24 | Udaipur | 50000 |
TEST CASE 2:- The following code is an example, which would fetch the all record from Customer table and sorted by the "Address" column in descending order.
SELECT * FROM Customer ORDER BY Address DESC;
The result for the respective sql query is as follows −
CustomerID | CustomerName | Age | Address | CustomerSalary |
---|---|---|---|---|
1 | Aarav | 28 | Udaipur | 28000 |
4 | Muhammad | 24 | Udaipur | 50000 |
2 | Vivaan | 25 | Mumbai | 30000 |
5 | Sai | 30 | Mumbai | 27000 |
3 | Reyansh | 28 | Chennai | 35000 |
Visit :
Discussion