Decode equivalent in postgres

前端 未结 3 694
一整个雨季
一整个雨季 2021-02-13 02:36

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

相关标签:
3条回答
  • 2021-02-13 03:00

    You can combine NULLIF with COALESCE:

    SELECT COALESCE(NULLIF(value, 0), newValue) FROM table;

    Font: Coalesce for zero instead of null

    0 讨论(0)
  • 2021-02-13 03:10

    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.

    0 讨论(0)
  • 2021-02-13 03:16

    If you are used to Oracle specific functions, you might want to install PostgreSQL extension orafce.

    Among other Oracle specific functions, orafce also implements DECODE - one that you are looking for.

    If you are running on Ubuntu, you will simply need to install package postgresql-9.1-orafce to make orafce available in your PostgreSQL server.

    0 讨论(0)
提交回复
热议问题