How to Sort Records in SQL
When you run a select statement the records, or rows, that are displayed are not guaranteed to be in a specific order. Usually, you will want to sort the records to make the report more meaningful. You will learn how to sort records in this topic.
To learn how to sort records in an SQL select statement, follow these steps:
- You'll need to setup the MySQL database tables. The instructions for the setup can be found in How to add comments in simple SQL selects. Follow steps 1 through 7 in this topic before proceeding to the next step.
- Now you will learn how to sort records.
- We will start by listing the city names and state abbreviations in the
Note that the city names are not sorted.
- Rerite the SQL statement to request that cities by displaying in ascending alphabetical order:
By adding the
order byclause we can specify that we want the report sorted by ascending city name.
- Now change the SQL statement to request that cities by displayed in descending alphabetical order:
desckeyword to request a descending sort (
ascfor ascending is the default).
- Let's alphabetize by state abbreviation ascending and within each state display the cities in descending sequence:
The report is in ascending state abbreviation sequence. For each state, the output is sorted in descending city name sequence. I've highlighted California as an example.