Check if anyelement ISNULL [ Postgresql ]

2.4k views Asked by At

I am Trying to implement the access function 'isnull' in postgresql this function takes as a parameter an expression and the function returns true if null has been passed, or false if it is not null. I know postgres has the 'IS NULL' and 'NOT NULL' keywords bu I keep getting polymorphic errors when passing either a string or a null value itself to the function as they are both unknown types.

This method has to be done using a function.

What I have so far:

CREATE OR REPLACE FUNCTION isnull( anyelement ) RETURNS anyelement as $$
    BEGIN
        IF $1 IS NULL THEN RETURN TRUE;
        ELSE RETURN FALSE;
        END IF;
    END
    $$LANGUAGE plpgsql;
2

There are 2 answers

0
Laurenz Albe On BEST ANSWER

If you define these two functions, it will work for all cases:

CREATE OR REPLACE FUNCTION isnull(anyelement) RETURNS boolean
   LANGUAGE sql IMMUTABLE AS 'SELECT $1 IS NULL';

CREATE OR REPLACE FUNCTION isnull(unknown) RETURNS boolean
   LANGUAGE sql IMMUTABLE AS 'SELECT $1::text IS NULL';

The additional advantage is that SQL functions like these can be inlined.

4
mike.k On

I got this to work

CREATE OR REPLACE FUNCTION isnull( anyelement ) RETURNS boolean as $$
BEGIN
    RETURN $1 IS NULL;
END
$$LANGUAGE plpgsql;

Test:

CREATE TEMP TABLE test(a int, b int);
INSERT INTO test VALUES (1, null), (2, null);
SELECT isnull(a), isnull(b) FROM test;

Gives:

 isnull | isnull
--------+--------
 f      | t
 f      | t