PostgreSQL ORDER BY Clause
In PostgreSQL, 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.The ORDER BY clause helps to change this sequence
ORDER Syntax :
The syntax of the ORDER statement is −
SELECT column1,column2 FROM table_name ORDER BY column1,column2 desc
ORDER Example :
Consider the STUDENT table is having the following records
ID | NAME | AGE | ADDRESS |
---|---|---|---|
1 | Jugal | 20 | Mysore |
2 | Kartik | 19 | Delhi |
3 | Ashish | 21 | Udaipur |
4 | Prateek | 19 | Jaipur |
5 | Pranjal | 20 | Mumbai |
6 | Vivek | 19 | Mumbai |
TEST CASE 1 :- The following code is an example, which would fetch the all record from STUDENT table and sorted by the "AGE" column.
SELECT * FROM STUDENT ORDER BY AGE ASC;
The result for the respective query is as follows −
ID | NAME | AGE | ADDRESS |
---|---|---|---|
2 | Kartik | 19 | Delhi |
4 | Prateek | 19 | Jaipur |
6 | Vivek | 19 | Mumbai |
1 | Jugal | 20 | Mysore |
5 | Pranjal | 20 | Mumbai |
3 | Ashish | 21 | Udaipur |
TEST CASE 2:- The following code is an example, which would fetch the all record from STUDENT table and sorted by the "NAME" column in descending order.
SELECT * FROM STUDENT ORDER BY NAME DESC;
The result for the respective query is as follows −
ID | NAME | AGE | ADDRESS |
---|---|---|---|
3 | Ashish | 21 | Udaipur |
1 | Jugal | 20 | Mysore |
2 | Kartik | 19 | Delhi |
5 | Pranjal | 20 | Mumbai |
4 | Prateek | 19 | Jaipur |
6 | Vivek | 19 | Mumbai |
Visit :
Discussion