Into Statement  «Prev  Next»
Lesson 7An introduction to the ORDER BY clause
ObjectiveLearn how the ORDER BY clause works

Sorting Rows with ORDER BY

Rows in a query result are unordered, so you should view the order in which rows appear as being arbitrary. This situation arises because the relational model posits that row order is irrelevant for table operations. You can use the ORDER BY clause to sort rows by a specified column or columns in ascending (lowest to highest) or descending (highest to lowest) order.
The ORDER BY clause always is the last clause in a SELECT statement.
Example 1: To sort by a column:
SELECT columns
FROM table
ORDER BY sort_column [ASC | DESC];
columns is one or more comma-separated column names, sort_column is the name of the column on which to sort the result, and table is the name of the table that contains columns and sort_column. (sort_column does not have to be in listed in columns.) Specify ASC for an ascending sort or DESC for a descending sort. If no sort direction is specified, ASC is assumed

The SQL in Example 2 lists the authors' first names, last names, cities, and states, sorted by ascending last name.
ORDER BY performs ascending sorts by default, so the ASC keyword is optional. (In practice, ASC typically is omitted.)
Example 2:
SELECT au_fname, au_lname, city, state
FROM authors
ORDER BY au_lname ASC;

Result of Select statement :This result is sorted in ascending last-name order.
Result of the select statement executed from Example 2:This result is sorted in ascending last-name order.

ORDER BY clause in SQL

If we return to Customer Table, shown below, we can see that there are a number of different ways to "slice and dice" the information presented.
LastnameFirstnamePhoneNumberZIP Code

It might be helpful to have the list sorted by last name. You sort, or order, information using the ORDER BY clause. Add this clause to your standard SELECT statement. So, if you want to return all rows from the table, you would use the following:

SELECT * FROM Customer 

This results in the table shown above. But what we want to do now is to sort this table based on the Lastname column.
This is quite straightforward:
SELECT * FROM Customer 
ORDER BY Lastname 

The result will be
Lastname Firstname PhoneNumber ZIP Code
Andrews Julie 309-123-4567 85744
Brennan Jeffrey 123-321-5678 04325
Caitlin Elizabeth 444-231-5642 95439
Wynsoup Stephen 520-555-1212 85744
Wynsoup Julie 201-453-7641 85744

This starts to make things a bit clearer. You can see that the Lastname column is now in alphabetical order. Notice, however, that the final two entries, both with the same last name, are not sorted by first name. They generally appear in the order that they were entered into the database table.