SQL ORDER BY - The Coding Shala
Home >> Learn SQL >> SQL ORDER BY
If we want in descending order then -
Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.
SQL ORDER BY
The SQL 'Order By' clause is used to sort the result in ascending a descending order based on the one or more columns. The ORDER BY sorts the result in ascending order by default.
SQL ORDER BY SYNTAX
The basic SQL order by syntax as follows -
SELECT column1, column2, .. FROM table_name [WHERE condition] ORDER BY column1, column2, ..[ASC | DESC];
SQL ORDER BY EXAMPLES
The following 'emp' table is used for the examples -
Id Name Age Address Salary 1 Akshay 22 Pune 40000 2 Mohit 21 Delhi 42000 3 Akash 21 Delhi 45000 4 Nikhil 24 Mumbai 50000 5 Smith 24 Pune 50000 6 Akshay 22 Pune 50000 7 Nikhil 24 Mumbai 43000
The following query sort the data based on the 'Age' -
SQL >> select * from emp order by Age; Output >> Id Name Age Address Salary 2 Mohit 21 Delhi 42000 3 Akash 21 Delhi 45000 1 Akshay 22 Pune 40000 6 Akshay 22 Pune 50000 4 Nikhil 24 Mumbai 50000 5 Smith 24 Pune 50000 7 Nikhil 24 Mumbai 43000
If we want in descending order then -
SQL >> select * from emp order by Age desc; Output >> Id Name Age Address Salary 4 Nikhil 24 Mumbai 50000 5 Smith 24 Pune 50000 7 Nikhil 24 Mumbai 43000 1 Akshay 22 Pune 40000 6 Akshay 22 Pune 50000 2 Mohit 21 Delhi 42000 3 Akash 21 Delhi 45000
- We can use the column position to sort the result, the position of the 'Age' column is 3.
- The following query will be used to sort the result based on the column position -
SQL >> select * from emp order by 3; Output >> Id Name Age Address Salary 2 Mohit 21 Delhi 42000 3 Akash 21 Delhi 45000 1 Akshay 22 Pune 40000 6 Akshay 22 Pune 50000 4 Nikhil 24 Mumbai 50000 5 Smith 24 Pune 50000 7 Nikhil 24 Mumbai 43000
- We can use order by on more than one column together.
- The following query is used to sort data based on 'Name, and 'Age' column -
SQL >> select * from emp order by Name, Age; Output >> Id Name Age Address Salary 3 Akash 21 Delhi 45000 1 Akshay 22 Pune 40000 6 Akshay 22 Pune 50000 2 Mohit 21 Delhi 42000 4 Nikhil 24 Mumbai 50000 7 Nikhil 24 Mumbai 43000 5 Smith 24 Pune 50000
Other Posts You May Like
Prev<< SQL GROUP BY NEXT >>SQL Primary Key
Comments
Post a Comment