Sub topic 12
Range Checks in DECODE with SIGN
Assume you know basic SELECT statements, Oracle numeric values, and the equality-based form of DECODE. This chapter shows how to use SIGN with DECODE when you need to classify a number relative to a threshold.
Why DECODE needs help with ranges
DECODE compares one expression with a list of search values. It is useful for equality:
DECODE(status_code,
1, 'Open',
2, 'Closed',
'Unknown')However, DECODE does not directly test conditions such as salary > 10000 or amount <= 500. It cannot contain a comparison operator inside a search value.
The SIGN function converts a number into a small set of values:
| Expression result | `SIGN` result |
|---|---|
| Negative number | -1 |
| Zero | 0 |
| Positive number | 1 |
Subtracting a threshold from a value turns a range comparison into one of these three results.
Classifying values around a threshold
The following query compares each salary with 10000. The expression salary - 10000 is negative when the salary is below the threshold, zero when it equals the threshold, and positive when it is above it.
WITH salary_values (employee_id, salary) AS (
SELECT 101, 7500 FROM dual UNION ALL
SELECT 102, 10000 FROM dual UNION ALL
SELECT 103, 12500 FROM dual
)
SELECT employee_id,
salary,
DECODE(
SIGN(salary - 10000),
-1, 'Below 10000',
0, 'Exactly 10000',
1, 'Above 10000',
'Unknown'
) AS salary_position
FROM salary_values
ORDER BY employee_id;The final string, 'Unknown', is the default result. It protects the expression if SIGN produces a value that is not listed. It also documents the intended fallback.
A simpler two-way test can combine the zero and negative cases:
SELECT employee_id,
salary,
DECODE(
SIGN(salary - 10000),
1, 'Above 10000',
'At or below 10000'
) AS salary_check
FROM employees;Here, only 1 has a special result. Both -1 and 0 use the default result.
NULL and boundary behavior
If salary is NULL, then salary - 10000 is also NULL, and SIGN(NULL) returns NULL. Oracle's DECODE treats a NULL expression as matching a NULL search value. You can handle that case explicitly:
SELECT employee_id,
salary,
DECODE(
SIGN(salary - 10000),
NULL, 'No salary',
-1, 'Below 10000',
0, 'Exactly 10000',
1, 'Above 10000',
'Unknown'
) AS salary_position
FROM employees;For more complex ranges, CASE is generally easier to read:
CASE
WHEN salary IS NULL THEN 'No salary'
WHEN salary < 10000 THEN 'Below 10000'
WHEN salary = 10000 THEN 'Exactly 10000'
ELSE 'Above 10000'
ENDKeep the boundary rules explicit. Decide whether a threshold belongs to the lower or upper band, and test the exact boundary value.
Exercise
What label does DECODE(SIGN(9500 - 10000), -1, 'Low', 0, 'Exact', 1, 'High', 'Unknown') return?
Show answer
It returns 'Low' because 9500 - 10000 is negative, and SIGN of a negative number is -1.