Oracle decode function
Oracle tips by Burleson
The most powerful of all of the BIFs are the Oracle decode and Oracle case function. The Oracle decode and case functions are used within the Oracle database to transform data values for one value to another.
One of the most amazing features of the case the Oracle decode statements is that they allow us to create an index on data column values that do not exist in the database.
Oracle started with the decode statement and later refined it in Oracle9i, morphing it into the case statement.
Let's take a look at how the decode statement works. The Oracle decode statement was developed to allow us to transform data values at retrieval time. For example, say we have a column named REGION, with values of N, S, W and E. When we run SQL queries, we want to transform these values into North, South, East and West. Here is how we do this with the decode function:
Note that Oracle decode starts by specifying the column name, followed by set of matched-pairs of transformation values. At the end of the decode statement we find a default value. The default value tells decode what to display if a column values is not in the paired list.
Here is the SQL to create this report in your pubs database:
p.pub_key = b.pub_key
This is a very important SQL statement because it demonstrates the nesting of BIFs and the use of decode for counting values. Let's take a closer look.
Once we have converted the column to a 0-1 numeric value, we pass the entire clause to the sum function, and add-up the numbers.
As we can see, the decode function is convoluted and hard to write. Oracle added the case function to SQL starting in Oracle9i to simplify this type of data transformation. The case statement is an easier form of the decode statement.
The power of these functions become apparent when combined with the decode built-in function. By using decode to change the ranges to a binary number, we can then use the sum built-in function to count the number of values within a specified range. The query below shows how this works:
prompt Salary ranges by Department
sum(decode(greatest(SAL,3001), least(SAL,9999), 1, 0)) "$3001-$9999",
sum(decode(greatest(SAL,2001), least(SAL,3000), 1, 0)) "$2001-$3000",
sum(decode(greatest(SAL,1001), least(SAL, 2000), 1, 0)) "$1001-$2000",
sum(decode(greatest(SAL, 0), least(SAL, 1000), 1, 0)) "< $1000"
Oracle documentation notes the following syntax for decode:
DECODE(expr, search, result
[, search, result ]...
[, default ]
Get the Complete
Oracle SQL Tuning Information
The landmark book
SQL Tuning The Definitive Reference" is
filled with valuable information on Oracle SQL Tuning.
This book includes scripts and tools to hypercharge Oracle 11g
performance and you can
for 30% off directly from the publisher.