How to Use DECODE in SQL Query and Its Real Purpose

The DECODE function’s real purpose is to handle logic scenarios. It works similarly to using the if-else-endif of any high-level programming language.

Table of contents

The syntax for the DECODE function

DECODE(expression1,expression2,result-expression,else-expression).

Here, the expression1 is “Column name”, and it compares with the next value. If it matches, replaces it with a third value.

SQL Query with DECODE

DECODE(c1, 7, 'a', 
 6, 'b', 'c')
DECODE(c1, var1, 'a', var2, 'b')

SELECT ID, DECODE(STATUS, 
 'A', 'Accepted',
 'D', 'Denied',
 CAST(NULL AS VARCHAR(1)), 'Unknown', 'Other')
FROM CONTRACTS

Related

Discover more from Srinimf

Subscribe now to keep reading and get access to the full archive.

Continue reading