Monday, March 14, 2016

SQL ORDER BY

Another important clause used along with SQL SELECT is the ORDER BY clause. ORDER BY defines in what order do we get the data we have requested. Here is an example of using SQL ORDER BY:

 SELECT * FROM Cars ORDER BY Year;

The SQL statement above will select all columns from the Cars table, and will order them by the Year column, returning a result like this:

CarMakeModelYearColor
HondaAccord EX2002Black
ToyotaCamry XLE2005Gray
BMW3 Series Coupe2008Red
LexusES 3502008Grayr

You can order by more than one column, by simply typing a comma-separated list of column names after the ORDER By clause. For example if you want to order by both Year and Color, you can use the following:

 SELECT * FROM Cars ORDER BY Year, Color; 

The result will be this:

CarMakeModelYearColor
HondaAccord EX2002Black
ToyotaCamry XLE2005Gray
LexusES 3502008Gray
BMW3 Series Coupe2008Red

The Gray Lexus goes on top of the red BMW even though they are the same year, because the Color column is ordered alphabetically and Gray goes first.


So far all ORDER BY statements above ordered the data alphabetically, but what if we want the data ordered backwards? To answer this question we must introduce ASC and DESC keywords. The ASC and DESC keywords determine the order in which the results are displayed. If you don't specify ASC or DESC after the ORDER BY clause, the SQL interpreter defaults the order to ascending, which means that the following 2 SQL statements yield the same result:

 SELECT * FROM Cars ORDER BY CarMake; 


 SELECT * FROM Cars ORDER BY CarMake ASC; 

And here is the result:

CarMakeModelYearColor
BMW3 Series Coupe2008Red
HondaAccord EX2002Black
LexusES 3502008Gray
ToyotaCamry XLE2005Gray

If you specify DESC instead of ASC in the SQL expression above, you will get this result:

CarMakeModelYearColor
ToyotaCamry XLE2005Gray
LexusES 3502008Gray
HondaAccord EX2002Black
BMW3 Series Coupe2008Red

You can specify ASC or DESC, after each column following ORDER BY. For example:

 SELECT * FROM Cars ORDER BY Year ASC, Color DESC; 

The result will be:

CarMakeModelYearColor
HondaAccord EX2002Black
ToyotaCamry XLE2005Gray
BMW3 Series Coupe2008Red
LexusES 3502008Gray

First the result set is ordered by Year ascending, and then for the rows having one and the same year as the BMW and Lexus ones, the Color column is ordered descending, that's why the Red BMW comes on top of the Gray Lexus.

0 comments:

Post a Comment

 
Animated Social Gadget - Blogger And Wordpress Tips