Projects | Downloads | Tickets | KnowledgeBase | Forums | About | Search
Load:0.00 0.00 0.00
Sessions: 21
Login
User:
Pass:
Remember login:
New User | Lost Password

Case[1144]: Oracle: order by in custom order

Printable View
Case
Title:Oracle: order by in custom order
Number:1144
Created:11/14/2008 11:08
Created By:bemowski
Page Views:2698
Status: ACTIVE
Approver:unassigned
Keywords:select order by oracle
Related Tickets:
Detail


Lets say I have a table with a column with a few distinct values. I want to select, and get the rows back in an order that reflects the object type defined in that column.

For instance, I have a table with 3 columns:

CREATE TABLE people
(first_name VARCHAR2(20),
last_name VARCHAR2(20),
occupation VARCHAR2(20));

Then, I add some rows:
insert into PEOPLE (FIRST_NAME,LAST_NAME,OCCUPATION)
values ('joe','the','plumber');

insert into PEOPLE (FIRST_NAME,LAST_NAME,OCCUPATION)
values ('bob','the','builder');

insert into PEOPLE (FIRST_NAME,LAST_NAME,OCCUPATION)
values ('babe','ruth','baseball player');

insert into PEOPLE (FIRST_NAME,LAST_NAME,OCCUPATION)
values ('john','mccain','senator');

insert into INVLOAD.PEOPLE (FIRST_NAME,LAST_NAME,OCCUPATION)
values ('bill','gates','developer');


Now, I want to order by their relative contributions to society. Now, I could add an additional column - that indicated this value (meaning to society). Or, I could create an occupation table that contains the value to society, and then join with that table, and order by it.

However, if there are relatively few possible values, and I want the order defined in the query rather than in tabular data, then I can simply do a custom order in SQL with the decode keyword. Decode maps keys to new values. Details of how it works should be obvious looking at this sql:
select * from people
order by decode(occupation, 'senator', 'a', 'developer', 'b', 'baseball player', 'c', 'shephard', 'd', 'z')


This retrieves the rows in alphabetical order according to my decoding indicating the ordering.


Add Comment


Show System Notes
User Date Comment
anonymous 01/06/2010
01:41
Wow! what a wonderful work you are doing
anonymous 09/29/2009
07:00
Wonderful
anonymous 07/01/2009
14:36
Thanks, very simple solution for this!
anonymous 06/22/2009
13:32
Thank you! I knew this had to be something that could be done, but NO ONE else discusses it.
Copyright 2003-2007, JMatrix International