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:

SELECT * FROM Weather ORDER BY City

The result of using this SQL ORDER BY clause will be the following:

CityAverageTemperatureDate
New York18 C10/09/2005
New York22 C10/10/2005
Seattle20 C10/09/2005
Seattle21 C10/10/2005
Washington17 C10/09/2005
Washington20 C10/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:

SELECT * FROM Weather ORDER BY City, Date

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:

SELECT * FROM Weather ORDER BY City


SELECT * FROM Weather ORDER BY City ASC

Here is how to use SQL ORDER BY along with DESC keyword:

SELECT * FROM Weather ORDER BY City DESC

The result will be:

CityAverageTemperatureDate
Washington20 C10/10/2005
Washington17 C10/09/2005
Seattle21 C10/10/2005
Seattle20 C10/09/2005
New York22 C10/10/2005
New York18 C10/09/2005

When ordering by more than one column, you can specify different ordering direction for each column, for example:

SELECT * FROM Weather ORDER BY City ASC, Date DESC