Lesson 8 | Ordering by more than one Column |
Objective | Given certain specifications, create a SELECT Statement that correctly sorts the information in a Table. |
Ordering by more than one Column
You can further refine your
ORDER BY
clause by including more than one column as sort criteria.
In the example we have been using here, it would be nice if the list was sorted first by last name, then by first name.
Heres the
SELECT
statement we will use:
SELECT * FROM Customer
ORDER BY Lastname, Firstname
By adding Firstname, that column will now be considered as a secondary sort order for the results. Here are the results from this query:
Lastname | Firstname | PhoneNumber | ZIP Code |
Andrews | Julie | 309-123-4567 | 85744 |
Brennan | Jeffrey | 123-321-5678 | 04325 |
Caitlin | Elizabeth | 444-231-5642 | 95439 |
Wynsoup | Julie | 201-453-7641 | 85744 |
Wynsoup | Stephen | 520-555-1212 | 85744 |
Now we have put the first name in its place, you can indicate any number of columns in your sort order, and they can be a mix of types. That is, they can be character data, numeric data, and so on. The engine will take care of sorting the information for you and returning the results.
Example of ordering by First Name descending:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
After executing the query below:
SELECT * FROM People
ORDER BY FirstName DESC, YearOfBirth ASC
The result set will be as follows:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Order By Clause - Exercise