Sub topic 1
Why queries need conditional logic
SQL is declarative. You describe the result you want, and Oracle decides how to produce it. Plain SELECT, WHERE and ORDER BY cover many queries. Sooner or later you need the value in a column to depend on a condition that is checked row by row. This chapter explains why that need arises, which Oracle tools meet it, and what to expect from the rest of the tutorial.
Prerequisites
This chapter assumes you already know the following:
- Basic
SELECTstatements withWHEREandORDER BY. - The common Oracle data types
NUMBER,VARCHAR2andDATE. - That
NULLmeans "unknown or missing", and that comparing anything toNULLwith=never gives true. GROUP BYand aggregate functions such asSUMandCOUNT.
The examples use the employees table from Oracle's sample HR schema. The columns used are employee_id, department_id, job_id, salary and commission_pct.
The problem: one row, different outputs
A WHERE clause decides whether a row appears in the result. It does not change what a row looks like. Many reporting tasks need the second thing:
- Turn a numeric department code into a readable label.
- Place each employee in a salary band such as Low, Medium or High.
- Show "No commission" when
commission_pctisNULL. - Sort job titles in business order instead of alphabetical order.
- Give different salary raises depending on the current salary.
- Count how many employees in each department earn above a threshold.
All of these have the same shape: if this condition holds, produce this value, otherwise produce that one. This is conditional logic, or if-then-else.
Doing it without conditional expressions
Without a conditional expression, you can split the problem into one query per category and combine the results with UNION ALL:
SELECT employee_id, 'Low' AS salary_band
FROM employees
WHERE salary < 5000
UNION ALL
SELECT employee_id, 'Medium'
FROM employees
WHERE salary >= 5000 AND salary < 10000
UNION ALL
SELECT employee_id, 'High'
FROM employees
WHERE salary >= 10000;This works, but it has three weaknesses:
- Repetition. The table is read three times, and every boundary appears in two places. If you change 10000 to 12000, you must edit two lines, and a missed edit silently produces wrong labels.
- Lost rows. An employee with a
NULLsalary matches none of the three conditions and disappears from the result. Nothing warns you. - No reuse. The band logic exists only in this query. You cannot put it in an
ORDER BY, inside an aggregate, or on the right side of anUPDATE ... SET.
A conditional expression solves all three problems. It is evaluated once per row, and the table is read once:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;Every row is returned. A NULL salary falls through both comparisons (they evaluate to unknown, not true) and lands in ELSE, which is a behaviour you should know about and plan for. Chapter by chapter, this tutorial covers how to control that.
What "expression" means here
The key idea is that CASE and DECODE are expressions. An expression is a piece of SQL that produces exactly one value. Because a conditional is an expression, you can place it wherever Oracle accepts a value:
| Location | What the conditional does there |
|---|---|
| `SELECT` list | Computes a derived column such as a label or a band |
| `WHERE` | Builds a filter whose logic depends on another column |
| `ORDER BY` | Defines a custom sort sequence |
| `GROUP BY` | Groups rows by a derived category |
| Inside `SUM`, `COUNT` and similar | Counts or adds only the rows that meet a condition |
| `UPDATE ... SET` | Writes a different new value per row in one statement |
You will work through each of these locations in a later chapter. For now, remember the rule: if a plain column or literal could appear there, a conditional expression can too.
The tools Oracle gives you
Oracle offers several ways to express conditional logic. They overlap, but each has a purpose.
| Tool | What it does | Standard SQL? |
|---|---|---|
| `CASE` (simple) | Compares one expression with a list of values and returns the result for the first equal value | Yes |
| `CASE` (searched) | Tests a list of arbitrary conditions and returns the result for the first true one | Yes |
| `DECODE` | Compact equality matching with search/result pairs and an optional default | No, Oracle only |
| `NVL`, `NVL2`, `COALESCE`, `NULLIF` | Shortcuts for the most common `NULL`-related conditions | `COALESCE` and `NULLIF` are standard; `NVL` and `NVL2` are Oracle only |
| PL/SQL `IF` and `CASE` statements | Control the flow of procedural code rather than returning a value in a query | No (PL/SQL) |
Oracle's recommended general-purpose choice is CASE. It is part of the SQL standard, it allows any condition, and it works the same in other databases. DECODE predates CASE in Oracle. You will meet it constantly in older code, so you need to read it fluently even if you prefer to write CASE.
A first look at each form
Do not worry about the details yet. Later chapters cover them one at a time. This preview shows how the same question looks in each form.
A simple CASE names the expression once and lists the values to match:
SELECT employee_id,
department_id,
CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 50 THEN 'Shipping'
ELSE 'Other'
END AS department_label
FROM employees;A searched CASE has no expression after the CASE keyword. Each WHEN holds its own full condition, which is what allows ranges and combined tests, as in the salary band query above.
DECODE gives the same result as the simple form above in a single function call:
SELECT employee_id,
DECODE(department_id,
10, 'Administration',
20, 'Marketing',
50, 'Shipping',
'Other') AS department_label
FROM employees;The first argument is the expression. After it come search/result pairs, and one final value without a partner is the default.
How a conditional expression is evaluated
For each row, Oracle works down the list of branches in the order you wrote them and stops at the first one that matches. The diagram shows this for the salary band example.
Three consequences follow from this model, and they cause most real-world bugs:
- Order matters. Because evaluation stops at the first match, the branches in the salary example form bands only because they are listed from smallest to largest. If you put
salary < 10000first, nobody would ever be labelled Low. - Only true counts. A condition that evaluates to false or unknown moves evaluation to the next branch. Unknown results come from comparisons involving
NULL. - There is always a result. If no branch matches and you wrote no
ELSE, the expression returnsNULL. It does not raise an error.
Why this matters for correctness
Conditional logic placed in the database has practical benefits:
- One pass over the data. Categorising, counting and pivoting happen inside a single query instead of in several queries or in application code.
- Less data movement. The database returns finished labels or totals, not raw rows for the application to process.
- One definition of the rule. A band or label is defined in one place in the SQL, or in a view built on it.
There are also costs. A long chain of branches is harder to read than a lookup table. If the mapping from codes to labels changes often, such as department names, a join to a reference table is better than a hard-coded CASE. Treat conditional expressions as the right tool for logic, and tables as the right tool for data.
What comes next
The rest of the tutorial builds on this foundation. The following chapters cover the simple and searched forms of CASE and the exact rules for choosing a branch. Next come NULL behaviour and DECODE, including how it differs from CASE when comparing NULL values, and how to rewrite one as the other. The later chapters cover using these expressions in different clauses, conditional aggregation, result data types, and the shortcuts NVL, NVL2, COALESCE and NULLIF. The tutorial ends with PL/SQL and a review of common pitfalls.
Exercise
A colleague rewrites the salary band query with CASE WHEN salary < 10000 THEN 'Medium' WHEN salary < 5000 THEN 'Low' ELSE 'High' END. What band does an employee earning 3000 receive, and why? What band does an employee with a NULL salary receive?
Show answer
The employee earning 3000 receives 'Medium'. Oracle checks the branches in the order written and stops at the first true condition, and 3000 < 10000 is true, so the 'Low' branch is never reached. The employee with a NULL salary receives 'High'. Both comparisons evaluate to unknown rather than true, so evaluation falls through to the ELSE branch.
Exercise
Name two weaknesses of the UNION ALL approach to salary bands compared with a single CASE expression.
Show answer
Any two of these: the table is read once per branch instead of once; each boundary value is written in two places, so editing one and missing the other gives wrong labels; rows with a NULL salary match none of the conditions and silently disappear; the logic cannot be reused inside ORDER BY, an aggregate or an UPDATE.