postgresqlpolymorphic-functions

Check if anyelement ISNULL [ Postgresql ]


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;

Solution

  • 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.