skip to Main Content

Other than coalesce(col1, 0) + coalesce(col2, 0) is there any built in shorthand function, like least, that will let me do null safe addition?

2

Answers


  1. The is nothing built in, but you can create your own:

    CREATE FUNCTION null_safe_sum(VARIADIC numeric[]) RETURNS numeric
    LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
    $$SELECT sum(n) FROM unnest($1) AS u(n)$$;
    
    SELECT null_safe_sum(1, 2, NULL, 7, NULL);
    
     null_safe_sum 
    ═══════════════
                10
    (1 row)
    

    This uses the fact that sum() ignores NULL values.

    Login or Signup to reply.
  2. That’s just coalesce(col1+col2, col1, col2, 0).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search