Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode equivalent in postgres

Tags:

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

like image 708
vmb Avatar asked Mar 07 '13 03:03

vmb


People also ask

What is the equivalent of Decode in PostgreSQL?

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

Is there decode in PostgreSQL?

The PostgreSQL DECODE() function takes input text which needs to be decoded and a parameter type in which the user wants it to decode. The parameter given to the PostgreSQL Decode() function should be the same as the type of the parameter used in the case of the PostgreSQL Encode() function.

What is NVL in PostgreSQL?

nvl(A, B) returns A if it judges A is not NULL, otherwise it returns B. The arguments have to be of the same type, or can be automatically converted to the same type. Otherwise explicit conversion is required. The coalesce arguments can be more than one, and the first non-NULL argument will be returned.

What is decode equivalent in SQL Server?

What is DECODE function in SQL? In Oracle, DECODE function allows us to add procedural if-then-else logic to the query. DECODE compares the expression to each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database.


2 Answers

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.

like image 87
Mitch Wheat Avatar answered Sep 22 '22 12:09

Mitch Wheat


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.

like image 35
mvp Avatar answered Sep 22 '22 12:09

mvp