MySQL Tutorials - Herong's Tutorial Examples - 4.40, by Dr. Herong Yang
ORDER BY Clause of a SELECT Statement
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
Another interesting function called FIELD() can also be used in the ORDER BY clause. FIELD(value, value_list) returns the position of a given value in a given value list. For example, if you want to return employees with first name of "Jean, Mary, John, Mike" and in this order, you can use the following SELECT statement:
SELECT name, department, age FROM employee WHERE name IN ('Jean', 'Mary', 'John', 'Mike') ORDER BY FIELD (name, 'Jean', 'Mary', 'John', 'Mike')
Table of Contents