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
nameprice
Keyboard25.00
Monitor199.00
Mouse15.00

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;
Note: ORDER BY can also reference a column's position number in the SELECT list or an alias defined earlier in the same statement.
Note: Combine ORDER BY with LIMIT, for example ORDER BY price DESC LIMIT 5, to efficiently fetch a 'top N' style result.

Exercise: MySQL Order By

What sort order does ORDER BY use when no direction is specified?