Question: When you use a GROUP BY clause with one or more columns, will the results be in the sorted order of GROUP BY columns (by default) or shall we use ORDER BY clause?
Answer: You may get lucky and find that your result set is sorted in the order of the GROUP BY columns, but we recommend always using the ORDER BY clause whenever sorting is required.
Example #1
SELECT department, depart_head, SUM(sales) as "Total sales" FROM order_details GROUP BY department, depart_head ORDER BY department;
This example would sort your results by department, in ascending order.
Example #2
SELECT department, depart_head, SUM(sales) as "Total sales" FROM order_details GROUP BY department, depart_head ORDER BY department desc, depart_head;
This example would first sort your results by department in descending order, then depart_head in ascending order.