MySQL – ORDER BY Clause
The ORDER BY clause is used in SQL to sort records. The result set may be arranged in ascending or descending order with this method. When we use the SELECT statement to query, the result is not arranged in an orderly manner. When the SELECT statement is combined with an ORDER BY clause, the result rows can be sorted.
Syntax
SELECT expressions FROM tables [WHERE conditions] ORDER BY expression [ ASC | DESC ];
expressions – This is the column or calculation that you wish to retrieve.
Tables – It is necessary to identify the tables from which records should be retrieved. It is necessary to list at least one table in the FROM clause.
WHERE conditions – This is optional. Conditions that must be met in order to select records.
ASC – This is optional. The result set is sorted ascendingly according to the expression (default, if the modifier provider is not specified).
DESC – This is optional. The result set is sorted by expression in descending order.
- If the ORDER BY clause does not include the ASC or DESC modifier, the results will be sorted by expression in ascending order. Using this method is equivalent to using the ORDER BY expression ASC.
- In MySQL, ORDER BY clauses can be used in SELECT, SELECT LIMIT, and DELETE LIMIT statements.
Example
If, for example, we have a table named “employees” and we wish to retrieve the first name, last name, and salary of all employees alphabetically by last name, we would use the following query:
SELECT first_name, last_name, salary FROM employees ORDER BY last_name;
Example
Default sort order is ascending (ASC), but it is also possible to specify descending order (DESC) by including the keyword DESC after the column name. The following query would be used if you wanted to retrieve the first name, last name, and salary of all employees descending in salary order:
SELECT first_name, last_name, salary FROM employees ORDER BY salary DESC;
Example
It is also possible to order the results of a query according to multiple columns. If, for example, we wish to retrieve the first name, last name, and salary of all employees alphabetically by last name, but in reverse order by first name, we would use the following query:
SELECT first_name, last_name, salary FROM employees ORDER BY last_name, first_name;