Oracle – Change the behavior of ORDER BY

There are times when you would like to order the results of a query in such a way that it cannot be accomplished by the default behavior of the order by clause. For example, let’s look at the following table:

tbl_families

FirstName LastName FamilyMember
Mark Smith child
John Smith husband
Susan Smith wife
Sophia Dice child
Craig Dice husband
Maria Dice wife

Let’s say you need to order this table in such a way, so that you get all the husbands first, then the wives and the children at the end. Obviously, descending or ascending ordering by the FamilyMember field will not do the job. The solution is to combine the order by clause with the Oracle’s decode clause. Here is the result:

SELECT FirstName, LastName, FamilyMember
FROM tbl_families
ORDER BY DECODE (FamilyMember, 'husband', 'A', 'wife', 'B', 'child', 'C', 'Z');
Friday, October 24th, 2008 SQL

No comments yet.

Leave a comment

*

Search

 

Archive

May 2012
M T W T F S S
« Mar    
 123456
78910111213
14151617181920
21222324252627
28293031  

Other