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:

  1. 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.
  2. Now you will learn how to sort records.
  3. We will start by listing the city names and state abbreviations in the Cities table:
    Unorted city names
    Note that the city names are not sorted.
  4. Rerite the SQL statement to request that cities by displaying in ascending alphabetical order:
    Sorted city names
    By adding the order by clause we can specify that we want the report sorted by ascending city name.
  5. Now change the SQL statement to request that cities by displayed in descending alphabetical order:
    Sorted city names in descending sequence
    Use the desc keyword to request a descending sort ( asc for ascending is the default).
  6. Let's alphabetize by state abbreviation ascending and within each state display the cities in descending sequence:
    Sorted state abbreviations and descending city names
    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.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.