What is the PostgreSQL equivalent for ISNULL()

2020-01-30 02:20发布

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 ?

5条回答
相关推荐>>
2楼-- · 2020-01-30 03:00

Try:

SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name
查看更多
Juvenile、少年°
3楼-- · 2020-01-30 03:07

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.

查看更多
Summer. ? 凉城
4楼-- · 2020-01-30 03:11
SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias

Or more idiomatic:

SELECT coalesce(field, 'Empty') AS field_alias
查看更多
可以哭但决不认输i
5楼-- · 2020-01-30 03:15

How do I emulate the ISNULL() functionality ?

SELECT (Field IS NULL) FROM ...
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-30 03:15

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.

查看更多
登录 后发表回答