Saturday, November 19, 2011

SQL - ORDER BY

The ORDER BY clause comes in handy when you want to sort your SQL result sets by some column(s). For example if you want to select all the persons from the already familiar Customers table and order the result by date of birth, you will use the following statement:

SELECT * FROM Customers
ORDER BY DOB

The result of the above SQL expression will be the following:

FirstName
LastName
Email
DOB
Phone
John
Smith
2/4/1968
626 222-2222
Steven
Goldfish
4/4/1974
323 455-4545
Paula
Brown
5/24/1978
416 323-3232
James
Smith
20/10/1980
416 323-8888

As you can see the rows are sorted in ascending order by the DOB column, but what if you want to sort them in descending order? To do that you will have to add the DESC keyword after your ORDER BY clause:

SELECT * FROM Customers
ORDER BY DOB DESC

The result of the SQL query above will look like this:

FirstName
LastName
Email
DOB
Phone
James
Smith
20/10/1980
416 323-8888
Paula
Brown
5/24/1978
416 323-3232
Steven
Goldfish
4/4/1974
323 455-4545
John
Smith
2/4/1968
626 222-2222

If you don't specify how to order your rows, alphabetically or reverse, than the result set is ordered alphabetically, hence the following to SQL expressions produce the same result:

SELECT * FROM Customers
ORDER BY DOB
SELECT * FROM Customers
ORDER BY DOB ASC

You can sort your result set by more than one column by specifying those columns in the ORDER BY list. The following SQL expression will order by DOB and LastName:

SELECT * FROM Customers
ORDER BY DOB, LastName

No comments:

Post a Comment