Conditional Logic Using `Decode()`

What is decode()?

DECODE() is a function that lets you write simple conditional logic inside a SQL expression, similar to a  CASE  or  if‑then‑else  chain but in one line.

General Syntax

DECODE(
	   expression,
       search1, result1, -- If expression = Search1, then return Result 1
       search2, result2,
       ...,
       default_result -- If no match, return defautl_result or NULL if ommitted
       )

Example:

SELECT
  name,
  DECODE(gender,
         'M', 'Male',
         'F', 'Female',
         'Other') AS gender_label
FROM employees;

Case comparable:

SELECT
  name,
  CASE gender
    WHEN 'M' THEN 'Male'
    WHEN 'F' THEN 'Female'
    ELSE 'Other'
  END AS gender_label
FROM employees;
Powered by Forestry.md