Search code examples
postgresqlsql-function

Specify parameter when assigning value in PostgreSQL function


I have a requirement like: Call a function with 2 parameters in different situations.

function => getSum(a, b)

here it can be like,

  • a has value but not b then it should be like getSum(a = value goes here)
  • b has value but not a then it should be like getSum(b = value goes here)
  • a and b have values then it should be like getSum(a, b)

a and b are uuid, and a and b are treated separately in the function.

Is it possible to specify a value to the parameter?


Solution

  • For that you would use default values:

    CREATE FUNCTION getsum(
       a uuid DEFAULT '...',
       b uuid DEFAULT '...'
    ) RETURNS ...
    

    You can call the function like this:

    SELECT getsum(b => '...');
    

    Then the default value will be used for a.