What is SQL ORDER BY ?
SQL ORDER BY is used to arrange the Query result into ascending and descending order. ORDER BY is also used in important SQL concepts like Windows functions. It works on both numerical and alphabetical values.
Syntax of ORDER BY :
SELECT * FROM demo_tab GROUP BY col ORDER BY col;
We will use the following table EMPLOYEE to showcase the use case of SQL ORDER BY-
SELECT * FROM EMPLOYEE ORDER BY SALARY;
Now the result set is ordered by SALARY
Order by and group by can be used with each other but user should keep in mind that GROUP BY comes first because of SQL order of execution.
SELECT DEPT_NAME, AVG(SALARY) FROM EMPLOYEE GROUP BY DEPT_NAME ORDER BY 2;
In the above example order by 2 means that order by second column specified in the SELECT statement.
ORDER BY DESC
ORDER BY can also be used to order values in descending order by using DESC keyword at the end. By default it is ascending.
SELECT * FROM EMPLOYEE ORDER BY SALARY DESC ;
You can see now SALARY is in descending order.
THANKS FOR READING!
SOURCE: Microsoft T-SQL documentation