The SQL 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 Company table and order the result by date of birth, you will use the following statement:
SELECT * FROM Company ORDER BY DOB
The result of the above SQL expression will be the following:
FirstName | LastName | Email | DOB | Phone |
Scott | Armstrong | Armstrong.yahoo.com | 2/4/1968 | 887-676-2321 |
Adam | Red | red@himail.com | 4/4/1978 | 792 343-2422 |
Santo | Harry | Harry@livingin.org | 5/24/1978 | 416 323-3232 |
Jackson | Jimmy | Jimmy@supermail.co.uk | 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 SQL keyword after your SQL ORDER BY clause:
SELECT * FROM Company ORDER BY DOB DESC
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 Company ORDER BY DOB
SELECT * FROM Company ORDER BY DOB ASC
You can sort your result set by more than one column by specifying those columns in the SQL ORDER BY list.
The following SQL expression will order by DOB and LastName:
No comments:
Post a Comment