Sorting Retrieved Column Data
By default, a SELECT query returns rows in no guaranteed order. The ORDER BY clause lets you sort the results by one or more columns, alphabetically, numerically, or chronologically, so the output is easier to read and analyze.
Questions you may have include:
- How do you sort query results?
- How do you sort in ascending or descending order?
- How do you sort by more than one column?
Basic sorting
Add ORDER BY after the table name, followed by the column to sort on:
SELECT first_name, last_name FROM customers ORDER BY last_name;
This lists customers alphabetically by last name. Sorting is ascending (A to Z, smallest to largest) unless you say otherwise.
Ascending and descending order
You can state the direction explicitly with ASC (ascending) or DESC (descending):
SELECT first_name, last_name FROM customers ORDER BY last_name DESC;
Here the results run from Z to A. DESC is often used to put the most recent dates or the highest numbers first.
Sorting by multiple columns
List several columns, separated by commas, to break ties. The database sorts by the first column, then uses the next column to order rows that share the same value:
SELECT first_name, last_name, city FROM customers ORDER BY city, last_name;
This groups customers by city, and within each city orders them by last name. Each column can have its own ASC or DESC.
Summary
Without sorting, the order of query results is not guaranteed. The ORDER BY clause sorts rows by one or more columns, ascending by default or descending with DESC. Listing several columns sorts within groups, which is useful for organized, readable reports.
