Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres unassigned record, is there a way to test for null?

Is there some way to test an unassigned record for null? (Sorry, sqlfiddle doesn't like my DO block.) Thanks.

DO
$$
DECLARE
r record;
BEGIN

r := null;

if r is null    -- ERROR:  record "r" is not assigned yet
then
end if;

END
$$;
like image 306
Emery Lapinski Avatar asked Jan 08 '23 04:01

Emery Lapinski


2 Answers

The error can be avoided by writing:

   select null into r;

or alternatively:

   r:=row(null);

such that r gets initialized with a tuple structure.

Still, be aware that record variables are unintuitive in other of ways concerning NULLs, and more generally hard to work with outside of their base use case (cursor-style iterating).

like image 164
Daniel Vérité Avatar answered Jan 16 '23 22:01

Daniel Vérité


If you wrap the test with an exception handler you can use the "not initialized" error to do the check for you.

DO $$
DECLARE
r record;
BEGIN

r := null;

  BEGIN
    IF r IS NOT NULL THEN
        raise notice 'R IS INITIALIZED';
    END IF;
  EXCEPTION
    WHEN OTHERS THEN
        raise notice 'R IS NOT INITIALIZED';
  END;

END
$$;
like image 39
Gary Avatar answered Jan 16 '23 20:01

Gary