Purpose
The DECODE function compares condition with each search value in sequence and returns the corresponding result.
If one or more
searchvalues are equal tocondition, it returns the value of the first matchingresult.If no
searchvalues are equal tocondition, it returns the value of thedefaultparameter. If thedefaultparameter is omitted, it returnsnull.
Syntax
DECODE (condition, search, result [, search, result ...][, default])
Parameters
condition, search, result, and default can be values or expressions of numeric data types (NUMBER, FLOAT, BINARY_FLOAT, or BINARY_DOUBLE) or character data types (CHAR, VARCHAR2, NCHAR, or NVARCHAR2).
Notice
If the first result is of a numeric data type, then result or default must also be of a numeric data type. Otherwise, an error is returned.
Return type
If the data type of the
resultvalue corresponding to the first matchingsearchvalue isCHAR,VARCHAR2,NCHAR, orNVARCHAR2, it returns a value of theVARCHAR2data type.If the data type of the
resultvalue corresponding to the first matchingsearchvalue is a numeric data type, it returns a value of the corresponding numeric data type.If none of the
searchvalues are equal tocondition:If the
defaultparameter is omitted, it returnsnull.If the data type of the
defaultparameter isCHAR,VARCHAR2,NCHAR, orNVARCHAR2, it returns a value of theVARCHAR2data type.
Examples
Use
DECODEto compare the values of5*3-2and3*4-1.obclient> SELECT DECODE(SIGN((5*3-2)-(3*4-1)),0,'Equal',1,'(5*3-2) is larger','(3*4-1) is larger') FROM DUAL; +----------------------------------------------------------------------+ | DECODE(SIGN((5*3-2)-(3*4-1)),0,'Equal',1,'(5*3-2) is larger','(3*4-1) is larger') | +----------------------------------------------------------------------+ | (5*3-2) is larger | +----------------------------------------------------------------------+ 1 row in setUse the
DECODEfunction to check whether the characterSexists in the data.obclient> SELECT DECODE(INSTR('CLARK','S'), 0, 'Does not contain S', 'Contains S') "CLARK", DECODE(INSTR('KING','S'), 0, 'Does not contain S', 'Contains S') "KING", DECODE(INSTR('MILLER','S'), 0, 'Does not contain S', 'Contains S') "MILLER", DECODE(INSTR('ADAMS','S'), 0, 'Does not contain S', 'Contains S') "ADAMS", DECODE(INSTR('FORD','S'), 0, 'Does not contain S', 'Contains S') "FORD", DECODE(INSTR('JONES','S'), 0, 'Does not contain S', 'Contains S') "JONES" FROM DUAL; +-------------+-------------+-------------+----------+-------------+----------+ | CLARK | KING | MILLER | ADAMS | FORD | JONES | +-------------+-------------+-------------+----------+-------------+----------+ | Does not contain S | Does not contain S | Does not contain S | Contains S | Does not contain S | Contains S | +-------------+-------------+-------------+----------+-------------+----------+ 1 row in set