SQL ORDER BY
The SQL ORDER BY clause defines in what order to return a data set retrieved with a SQL SELECT statement. Here is an example of using SQL ORDER BY to order the rows in our Weather table by city:
The result of using this SQL ORDER BY clause will be the following:
City | AverageTemperature | Date |
New York | 18 C | 10/09/2005 |
New York | 22 C | 10/10/2005 |
Seattle | 20 C | 10/09/2005 |
Seattle | 21 C | 10/10/2005 |
Washington | 17 C | 10/09/2005 |
Washington | 20 C | 10/10/2005 |
As you can see we just ordered the data by the city column.
You can order the result of a SQL SELECT query by more than one column, for example:
SQL table columns may have different data types like varchar (a string of characters), datetime, int, etc. and for each of those types the SQL ORDER BY clause has somewhat different behavior. When you use SQL ORDER BY with varchar for example the result will be ordered alphabetically. With the int type the result will be ordered from the low to high number and with the date from dates in the past to later dates. Of course there are other SQL data types that can be used with ORDER BY, but this goes beyond the scope of this tutorial.
There are two SQL keywords that augment the SQL ORDER BY clause and define the direction of the ordering. The two keywords are ASC and DESC. When none of these two SQL keywords is specified after the ORDER BY SQL clause then it's assumed that we are using ASC (ordering alphabetically and from low to high). The following two SQL ORDER BY statements are equivalent:
Here is how to use SQL ORDER BY along with DESC keyword:
The result will be:
City | AverageTemperature | Date |
Washington | 20 C | 10/10/2005 |
Washington | 17 C | 10/09/2005 |
Seattle | 21 C | 10/10/2005 |
Seattle | 20 C | 10/09/2005 |
New York | 22 C | 10/10/2005 |
New York | 18 C | 10/09/2005 |
When ordering by more than one column, you can specify different ordering direction for each column, for example: