Sub topic 6
DECODE: Oracle's compact value-matching function
This chapter assumes you can write basic SELECT statements with WHERE and ORDER BY, know the common Oracle data types (NUMBER, VARCHAR2, DATE), and know that NULL means "unknown or missing". It also assumes you have seen the CASE expression in earlier chapters. The examples use the employees table from Oracle's HR sample schema.
What DECODE does
DECODE is an Oracle SQL function that compares one expression with a list of search values and returns the result paired with the first match. It is older than CASE and is specific to Oracle. Many existing Oracle codebases use it, so you need to read it fluently even if you write new code with CASE.
The syntax is:
DECODE(expr, search1, result1 [, search2, result2 ...] [, default])| Argument | Meaning |
|---|---|
| `expr` | The value to test. Evaluated once. |
| `searchN` | A value compared with `expr` for equality. |
| `resultN` | The value returned when `searchN` matches. |
| `default` | Optional. Returned when no search value matches. |
You can pass at most 255 arguments in total, counting expr, every search and result, and the default.
A first example
This query labels departments. It gives the same output as the simple CASE example from the earlier chapter.
SELECT employee_id,
DECODE(department_id,
10, 'Administration',
20, 'Marketing',
50, 'Shipping',
'Other') AS department_label
FROM employees;Read it as "if department_id equals 10, return 'Administration'; otherwise if it equals 20, return 'Marketing', and so on; if nothing matches, return 'Other'."
The equivalent simple CASE is longer but states each part by keyword:
SELECT employee_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
ELSE 'Other'
END AS department_label
FROM employees;How DECODE evaluates
DECODE works through its arguments in a fixed order:
- It evaluates
expronce. - It evaluates
search1and compares it withexpr. If they are equal, it returnsresult1and stops. - Otherwise it moves on to
search2, and so on, left to right. - If no search value matches, it returns the
default. If you did not supply a default, it returns NULL.
Three consequences follow from this order.
- First match wins. If two search values are equal, the second pair never runs.
- Later arguments are not evaluated after a match. Oracle evaluates each search value only when it is about to compare it. An expression in a later pair is never evaluated once an earlier pair has matched.
- A missing default gives NULL, not an error. A typo in a search value can therefore produce a column full of NULLs with no warning.
You can tell whether a default is present by counting arguments. With expr plus complete search/result pairs, the total is odd and there is no default. An even total means the last argument is the default.
SELECT DECODE(2, 1, 'one', 2, 'two', 'many') AS with_default,
DECODE(3, 1, 'one', 2, 'two') AS without_default
FROM dual;The first column returns two. The second returns NULL, because 3 matches nothing and no default was given.
Data types in DECODE
DECODE has implicit conversion rules that CASE does not. These are the source of most surprises.
- Search values are converted to the type of the first search value. Oracle converts
exprand each later search value to the data type ofsearch1before comparing. Ifsearch1is a number andexpris a string that does not look like a number, the query fails withORA-01722: invalid number. - The return type follows the first result. If the first result is character data, or is NULL, the return value is VARCHAR2. Other results are converted to that type.
- Character comparison is nonpadded. When
exprand a search value are both character data, Oracle compares them without blank padding, so'A'and'A 'are different.
The following query shows the first rule. Because the first search value is a number, the string '50' is converted to a number and matches.
SELECT DECODE('50', 50, 'fifty', 'other') AS conversion_demo
FROM dual;The result is fifty. The same query with 'abc' as the first argument raises ORA-01722.
A mismatch between the first result and later results is also easy to miss. In DECODE(x, 1, 'one', 2, 2), the second result is silently converted to the character string '2'. A simple CASE with the same results raises ORA-00932 instead. The failure is less visible in DECODE, so keep every result the same type.
Nesting DECODE
DECODE can test only equality, so a multi-step decision needs nesting. Each inner DECODE becomes the result or default of an outer one.
SELECT employee_id,
department_id,
job_id,
DECODE(department_id,
50, DECODE(job_id,
'ST_MAN', 'Shipping manager',
'ST_CLERK', 'Shipping clerk',
'Other shipping'),
90, 'Executive',
'Other department') AS role_label
FROM employees;This is already hard to scan with two levels. A searched CASE with AND conditions expresses the same rule with less indentation. If you find yourself nesting more than two levels, rewrite the logic as CASE.
Where you can use DECODE
DECODE is a SQL function, so it works anywhere a SQL expression is allowed. That includes the select list, WHERE, ORDER BY and GROUP BY, and the SET clause of UPDATE. It also works inside aggregate functions, which was the usual way to pivot rows into columns before CASE was added to Oracle SQL.
SELECT department_id,
COUNT(*) AS headcount,
SUM(DECODE(job_id, 'ST_CLERK', 1, 0)) AS clerks,
SUM(DECODE(job_id, 'SA_REP', 1, 0)) AS sales_reps
FROM employees
GROUP BY department_id
ORDER BY department_id;Each row contributes 1 to the column whose job matches and 0 to the other. You will see this pattern in older reports. The conditional aggregation chapter covers the same technique with CASE.
DECODE also works in ORDER BY to impose a custom sort order:
SELECT employee_id, job_id
FROM employees
ORDER BY DECODE(job_id, 'AD_PRES', 1, 'AD_VP', 2, 3),
employee_id;What DECODE cannot do
DECODE compares for equality only. It has no <, >, BETWEEN, LIKE or IN. Range logic therefore needs a workaround, which a later chapter covers with SIGN. It also cannot test two different columns in different branches, because every comparison uses the same expr. A rule such as "salary under 5000, or commission present" needs a searched CASE.
Another limit is portability. DECODE is Oracle-only, so SQL that uses it does not run unchanged on PostgreSQL, SQL Server or MySQL. CASE is part of the SQL standard and works on all of them.
Common errors
| Symptom | Likely cause |
|---|---|
| A column is NULL for many rows | No default was supplied and the search values missed those rows. |
| `ORA-01722: invalid number` | `expr` is a string and the first search value is a number. |
| `ORA-00938: not enough arguments for function` | Fewer than three arguments were passed. DECODE needs at least `expr`, one search value and one result. |
| Wrong label for some rows | Duplicate or overlapping search values. The first pair wins. |
| Unexpected result with `'A'` and `'A '` | Nonpadded comparison treats trailing blanks as significant. |
Exercise
What does this query return for the row with departmentid = 90, and what does it return for departmentid = 60? Explain why. SELECT DECODE(department_id, 90, 'Executive', 60, 'IT') AS label FROM employees;
Show answer
For department 90 it returns 'Executive', because 90 matches the first search value. For department 60 it returns 'IT'. Check the argument count: department_id plus two pairs is five arguments, which is odd, so there is no default. For a department such as 50 that matches no search value, the result is NULL. Adding a final default value, for example 'Other', would return that value instead of NULL.
Exercise
Rewrite the following DECODE call as a simple CASE expression. DECODE(jobid, 'ADPRES', 'President', 'AD_VP', 'Vice President', 'Staff')
Show answer
CASE jobid WHEN 'ADPRES' THEN 'President' WHEN 'AD_VP' THEN 'Vice President' ELSE 'Staff' END