MySQL Order By
ORDER BY sorts the result set of a query into ascending or descending order based on one or more columns.
Sorting Results with ORDER BY
ORDER BY is placed at the end of a SELECT statement, after any WHERE clause, and sorts the returned rows by one or more columns. Results are sorted in ascending order (ASC) by default; add DESC after a column name to sort that column in descending order instead.
Sorting by Multiple Columns
When you list more than one column in ORDER BY, MySQL sorts by the first column first, then uses the second column only to break ties within groups of equal values in the first, and so on. Each column in the list can independently be ASC or DESC.
- Alphabetical listings, such as sorting customers by name
- Most-recent-first feeds, sorting by a date column DESC
- Price comparisons, sorting products from cheapest to most expensive
- Leaderboards, sorting scores DESC with ties broken by an earlier timestamp
- Grouped reports, sorting by department ASC and then salary DESC within each department
Query Examples
Sort from lowest price to highest
SELECT * FROM products ORDER BY price ASC;Sort from highest price to lowest
SELECT * FROM products ORDER BY price DESC;Sort by two columns
SELECT * FROM employees ORDER BY department ASC, salary DESC;Exercise: MySQL Order By
What sort order does ORDER BY use when no direction is specified?