// conditional reference

Oracle DECODE function

Oracle's compact value matcher: DECODE(status, 'A', 'Active', 'I', 'Inactive', 'Unknown') checks the search values in order and returns the paired result, or the default. It is Oracle-only.

Catégorie
Conditionnel
Returns
type of the first result
In this category
6 of 43

Syntaxe

DECODE(expr, search1, result1 [, search2, result2 ...] [, default])

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in no DECODE; use CASE
PostgreSQL Not built in no DECODE; use CASE
MySQL Not built in no DECODE in MySQL 8; the 5.7 DECODE() was an unrelated decryption function, now removed
SQLite Not built in no DECODE; use CASE or IIF
Oracle Oui Supported under this name.

Exemples

Oracle

SELECT DECODE(status, 'A', 'Active', 'I', 'Inactive', 'Unknown') AS label
FROM accounts;

Oracle

-- NULL matching, which CASE cannot express with =
SELECT DECODE(manager_id, NULL, 'No manager', 'Has manager') AS flag
FROM employees;

Bon à savoir

  • DECODE treats two NULLs as equal, so a NULL search value matches a NULL input. A simple CASE x WHEN NULL never matches; you need a searched CASE with WHEN x IS NULL.
  • The result type follows the first result: if it is a number, a later result like 'x' raises ORA-01722 on the rows that return it; if it is NULL, the result is VARCHAR2.
  • MySQL 5.7 had a DECODE() that decrypted strings made by ENCODE(). It was removed in MySQL 8.0, and it never did what Oracle's does; port Oracle DECODE to CASE.

Questions about DECODE

Is DECODE available outside Oracle?

Not as a conditional. SQL Server, MySQL 8 and SQLite have no DECODE. PostgreSQL's decode(text, format) turns base64 or hex text into bytes, which is unrelated. CASE is the portable replacement.

How does DECODE handle NULL?

Unlike CASE, DECODE considers two NULLs equal: DECODE(col, NULL, 'missing', 'present') works, where CASE WHEN col = NULL never matches. Use IS NULL in CASE instead.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.