What is the PostgreSQL equivalent for ISNULL()

Sql ServerPostgresqlNull

Sql Server Problem Overview


In MS SQL-Server, I can do:

SELECT ISNULL(Field,'Empty') from Table

But in PostgreSQL I get a syntax error. How do I emulate the ISNULL() functionality ?

Sql Server Solutions


Solution 1 - Sql Server

SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias

Or more idiomatic:

SELECT coalesce(field, 'Empty') AS field_alias

Solution 2 - Sql Server

Use COALESCE() instead:

SELECT COALESCE(Field,'Empty') from Table;

It functions much like ISNULL, although provides more functionality. Coalesce will return the first non null value in the list. Thus:

SELECT COALESCE(null, null, 5); 

returns 5, while

SELECT COALESCE(null, 2, 5);

returns 2

Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.

Solution 3 - Sql Server

> How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...

Solution 4 - Sql Server

Try:

SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name

Solution 5 - Sql Server

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
	"is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionByron WhitlockView Question on Stackoverflow
Solution 1 - Sql ServerKyle ButtView Answer on Stackoverflow
Solution 2 - Sql ServerJim ClouseView Answer on Stackoverflow
Solution 3 - Sql ServerArturView Answer on Stackoverflow
Solution 4 - Sql Serveruser2718914View Answer on Stackoverflow
Solution 5 - Sql Serveruser287679View Answer on Stackoverflow