Ordering MySQL Data

Request data in ascending or descending order with ORDER BY

businessman hot-desking in an open plan office.
Ezra Bailey / Getty Images

When you query a MySQL database, you can sort the results by any field in an ascending or descending order just by adding ORDER BY at the end of your query. You use ORDER BY field_name ASC for an ascending sort (which is the default) or ORDER BY field_name DESC for a descending sort. You can use an ORDER BY clause in a SELECT statement, SELECT LIMIT or DELETE LIMIT statement. For example:

SELECT *
FROM address
ORDER BY name ASC;

The code above retrieves data from an address book and sorts the results by the person's name in an ascending fashion.

SELECT email
FROM address
ORDER BY email DESC;

This code selects only the email addresses and lists them in descending order.

Note: If you don't use an ASC or DESC modifier in the ORDER BY clause, the data is sorted by expression in ascending order, which is the same as specifying ORDER BY expression ASC.

Format
mla apa chicago
Your Citation
Bradley, Angela. "Ordering MySQL Data." ThoughtCo, Jul. 20, 2017, thoughtco.com/ordering-mysql-data-2693870. Bradley, Angela. (2017, July 20). Ordering MySQL Data. Retrieved from https://www.thoughtco.com/ordering-mysql-data-2693870 Bradley, Angela. "Ordering MySQL Data." ThoughtCo. https://www.thoughtco.com/ordering-mysql-data-2693870 (accessed May 21, 2018).