MySQL Tutorials - Herong's Tutorial Examples - Version 4.20, by Dr. Herong Yang
ORDER BY Clause of a SELECT Statement
This section provides tutorial examples on how to use the ORDER BY clause to sort rows of the base table according to the given order.
"ORDER BY clause" modifies the base table by sorting rows according the specified order. "ORDER BY clause" syntax is:
ORDER BY order_exp, order_exp, ...
where "order_exp" specify a single order expression. If multiple order expressions are specified, the order expression on the left has higher precedence than the one on the right. This means the order expression on the right will only be used to sort rows that are having the same for the order expression on the left.
If ORDER BY clause is used with GROUP BY clause, it must contain only group columns or group functions. For example, the following statement shows us which department has the oldest average age:
SELECT department, COUNT(name) AS numberOfEmployees, min(age) AS minimumAge, max(age) AS maximumAge, AVG(age) as averageAge FROM employee WHERE status='Active' GROUP BY department ORDER BY AVG(age) DESC
Last update: 2015.
Table of Contents