sqloracle-databasepostgresql

Decode equivalent in postgres


There is no equivalent to the Oracle's DECODE() Function In Postgres. Is there anyone who wrote decode as a Function?


Solution

  • There is an equivalent. It's called a CASE statement.

    There are two forms of CASE:

    Simple CASE:

    CASE search-expression
        WHEN expression [, expression [ ... ]] THEN
          statements
      [ WHEN expression [, expression [ ... ]] THEN
          statements
        ... ]
      [ ELSE
          statements ]
    END CASE;
    

    Searched CASE:

    CASE
        WHEN boolean-expression THEN
          statements
      [ WHEN boolean-expression THEN
          statements
        ... ]
      [ ELSE
          statements ]
    END CASE;
    

    CASE statements are easier to read; I prefer these over decode() in Oracle.