Sub topic 15
Common pitfalls and best practices
This chapter collects the mistakes that most often break CASE and DECODE code in Oracle, and the habits that prevent them. It assumes you can write simple and searched CASE, call DECODE, and use GROUP BY with aggregates. The examples use the employees table from the HR sample schema.
Quick reference
| Pitfall | Symptom | Fix |
|---|---|---|
| `WHEN NULL` in a simple `CASE` | Branch never runs | Use a searched `CASE` with `IS NULL` |
| Overlapping conditions in the wrong order | Rows land in the wrong band | Put the most specific test first |
| Missing `ELSE` | `NULL` appears in the output | Write `ELSE` every time, even if it is `ELSE NULL` |
| Mixed result types | ORA-00932 | Convert every branch to one type |
| `DECODE` with `SIGN` on a `NULL` | `NULL` falls into the default | Test `IS NULL` first, or use `CASE` |
| `ELSE 0` inside `COUNT` | Count equals total rows | Omit `ELSE` inside `COUNT` |
| `CASE` in `UPDATE` without `ELSE` | Column set to `NULL` | End with `ELSE column_name` |
NULL traps
A simple CASE compares with =. Any comparison with NULL is unknown, not true, so this branch can never run:
SELECT employee_id,
CASE commission_pct
WHEN NULL THEN 'No commission'
ELSE 'Has commission'
END AS label
FROM employees;Every employee gets 'Has commission', including those whose commission is NULL. Oracle does not raise an error, so the bug is silent. Use a searched CASE:
SELECT employee_id,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
ELSE 'Has commission'
END AS label
FROM employees;DECODE behaves differently. It treats two NULL values as equal, so DECODE(commission_pct, NULL, 'No commission', 'Has commission') works. When you convert between the two, this difference is the main thing to check.
SIGN and NULL
DECODE is often paired with SIGN for range checks. SIGN(NULL) is NULL, and DECODE finds no match for it among the non-null search values, so the default is returned:
SELECT employee_id,
salary,
DECODE(SIGN(salary - 10000),
1, 'Above 10000',
'At or below 10000') AS salary_check
FROM employees;An employee with a NULL salary is reported as "At or below 10000". That label is wrong, because the salary is unknown. A searched CASE lets you handle the unknown value explicitly:
SELECT employee_id,
salary,
CASE
WHEN salary IS NULL THEN 'Unknown'
WHEN salary > 10000 THEN 'Above 10000'
ELSE 'At or below 10000'
END AS salary_check
FROM employees;Branch order and the missing ELSE
Oracle returns the result of the first true branch and stops. If conditions overlap, order decides the outcome:
SELECT employee_id,
salary,
CASE
WHEN salary < 10000 THEN 'Medium'
WHEN salary < 5000 THEN 'Low'
ELSE 'High'
END AS salary_band
FROM employees;The 'Low' branch is unreachable, because every salary below 5000 is also below 10000. Write range conditions from the narrowest to the widest, or give each branch a lower and an upper bound when the bands need to be readable on their own.
If no branch matches and there is no ELSE, the expression returns NULL. That is legal, but it is rarely what you intend. Always write the ELSE, even when the answer is ELSE NULL, so the reader can see you chose it.
Mixed result types and ORA-00932
All result expressions in a CASE must be the same data type family. Numeric types can mix with each other. A number and a string cannot:
SELECT employee_id,
CASE
WHEN salary < 5000 THEN 'Low'
ELSE salary
END AS salary_info
FROM employees;This fails with ORA-00932: inconsistent datatypes: expected CHAR got NUMBER. Convert explicitly:
SELECT employee_id,
CASE
WHEN salary < 5000 THEN 'Low'
ELSE TO_CHAR(salary)
END AS salary_info
FROM employees;DECODE is more lenient and more surprising. The data type of its first result decides the return type, and the other results are implicitly converted to it. If the first result is a string, a numeric result later in the list is silently turned into text. That conversion can change how the column sorts, because '100' sorts before '20'. Do not rely on implicit conversion in either construct. Convert with TO_CHAR, TO_NUMBER or TO_DATE and state the format.
Aggregates
ELSE 0 inside COUNT
COUNT(expression) counts rows where the expression is not NULL. A 0 is not NULL:
SELECT department_id,
COUNT(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS wrong_count,
COUNT(CASE WHEN salary >= 10000 THEN 1 END) AS high_earners,
SUM(CASE WHEN salary >= 10000 THEN 1 ELSE 0 END) AS also_high_earners
FROM employees
GROUP BY department_id
ORDER BY department_id;wrong_count equals the number of employees in each department, because every row yields 1 or 0. COUNT needs a NULL for the rows to skip, so leave ELSE out. SUM needs a 0, so keep ELSE 0 there.
SUM over an empty or all-NULL group
SUM(CASE WHEN ... THEN salary END) returns NULL, not 0, for a group with no matching rows. If the report needs a zero, wrap the result: NVL(SUM(CASE ... END), 0). This applies to the pivot pattern from the previous chapter as well.
UPDATE and WHERE
In an UPDATE, a CASE without an ELSE sets unmatched rows to NULL:
UPDATE employees
SET salary = CASE
WHEN salary < 5000 THEN salary * 1.10
WHEN salary < 10000 THEN salary * 1.05
END
WHERE department_id = 50;Every employee in department 50 with a salary of 10000 or more now has a NULL salary. End the expression with ELSE salary, and run the statement as a SELECT first to check the output.
Be careful with CASE inside a WHERE clause. It works, but WHERE CASE WHEN a = 1 THEN b ELSE c END = 5 is hard to read and usually prevents the optimizer from using an index on b or c. Rewrite it as plain AND/OR conditions when you can.
PL/SQL: statement versus expression
In PL/SQL, a CASE statement with no matching WHEN and no ELSE raises CASE_NOT_FOUND (ORA-06592). A CASE expression with the same gap returns NULL. The two forms look alike, and the statement form is the one that ends with END CASE.
DECLARE
v_grade VARCHAR2(1) := 'Z';
v_text VARCHAR2(20);
BEGIN
CASE v_grade
WHEN 'A' THEN v_text := 'Excellent';
WHEN 'B' THEN v_text := 'Good';
END CASE;
DBMS_OUTPUT.PUT_LINE(v_text);
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No branch matched');
END;
/Choosing the right tool
COALESCE(a, b, c) returns the first non-null argument and evaluates arguments only as needed. NULLIF(a, b) returns NULL when the two values are equal, which gives a short guard against division by zero: total / NULLIF(count_value, 0).
Best practices
- Prefer
CASEoverDECODEin new code. It follows the SQL standard, supports ranges, and is easier to read. - Always write an
ELSE, and decide what the "unexpected value" result should be. - Handle
NULLfirst, with anIS NULLbranch at the top of a searchedCASE. - Give every branch the same data type, converting explicitly.
- Keep conditions mutually exclusive when you can, so the order of branches does not carry hidden meaning.
- Alias the result column. An unnamed expression gets its full text as the column heading.
- Keep expressions short. Past about six branches, a lookup table joined to the query is easier to maintain.
- Test with edge rows:
NULLvalues, boundary values such as exactly 5000, and values that match no branch.
Exercise
This query is meant to count the employees in each department who have a commission. It returns the total headcount for every department. Explain why, and write the corrected query. SELECT departmentid, COUNT(CASE WHEN commissionpct IS NOT NULL THEN 1 ELSE 0 END) AS withcommission FROM employees GROUP BY departmentid;
Show answer
COUNT(expression) counts every row where the expression is not NULL. The CASE returns 1 or 0, and neither is NULL, so every row is counted. Remove the ELSE so that rows without a commission yield NULL and are skipped: COUNT(CASE WHEN commission_pct IS NOT NULL THEN 1 END). SUM(CASE WHEN commission_pct IS NOT NULL THEN 1 ELSE 0 END) also works. Even simpler, COUNT(commission_pct) gives the same result.
Exercise
A query uses DECODE(SIGN(salary - 10000), 1, 'High', 'Not high'). An employee has a NULL salary and is labelled 'Not high'. Rewrite the expression as a searched CASE that labels that employee 'Unknown'.
Show answer
CASE
WHEN salary IS NULL THEN 'Unknown'
WHEN salary > 10000 THEN 'High'
ELSE 'Not high'
END
SIGN(NULL) is NULL, which matches none of the DECODE search values, so the default is returned. The IS NULL branch must come first.