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

  1. The syntax for the DECODE function
  2. SQL Query with DECODE

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

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.