1. SQL ORDER BY Clause:
The SQL ORDER BY Clause is used in a SELECT statement to sort results either in ascending or descending order.
Syntax for using SQL ORDER BY clause to sort data is:
>SELECTcolumn-list FROM table_name ORDER BY column1, column2,.. columnN [DESC]];
If you want to sort the employee table by salary of the employee, the SQL query would be.
> SELECT name, salary FROM employee ORDER BY salary;
By default, the ORDER BY Clause sorts data in ascending order. If data to be sorted in descending order, the command would be as given below.
> SELECT name, salary FROM employee ORDER BY name, salary DESC;
2. SQL GROUP BY Clause:
The SQL GROUP BY Clause is used with the group functions to retrieve data grouped according to one or more columns.
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2 FROM table name WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
If you want to know the total amount of salary spent on each department, the query would be:
> SELECT dept, SUM (salary) FROM employee GROUP BY dept;
The group by clause should contain all the columns in the select list expect those used along with the group functions.
> SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept;