Thursday, July 12, 2007

Oracle's DECODE funtion...

Oracle's decode function can be used to create arbitrary ORDER BY clauses. This is useful if you are providing lists with the most frequently picked value at the top - e.g. a list of countries which starts with 'United States' and then turns into a conventional alphabetical listing. Your SELECT statement will have two things in the ORDER BY clause - first it sorts by a DECODE that turns your favoured value into '1' and all other values into '2' and then it sorts the rest of the list conventionally. The alternatives to using DECODE are to hard code the entire list (bad!) or add a numeric column to the underlying table that defines the sort order, which is a lot more work than a DECODE in an ORDER BY.


SQL> r



1 select country_name


2 from iso_countries


3* order by decode(country_name,'UNITED STATES',1,2)

  , country_name





COUNTRY_NAME


--------------------------------------------------


UNITED STATES


AFGHANISTAN


ALBANIA


ALGERIA


AMERICAN SAMOA


ANDORRA


ANGOLA


ANGUILLA


ANTARCTICA


ANTIGUA AND BARBUDA


ARGENTINA


...





This behavior is common for web sites where drop down lists have to be dynamic (the contents may change) but also require location or market specific default preferences.





While we're on the subject of lists of countries one really should think twice before including Bouvet Island one's list...

Labels:

0 Comments:

Post a Comment

<< Home

Privacy Policy
Legal Terms
Site Map
About Us