Search code examples
postgresqlfunctionif-statementparametersnull

Postgres function parameter is null then replace it with default value


I have a postgres function

 create or replace function start_batch(in start_date date, int end_date date) returns integer 
as $batch$

BEGIN
    
    if(start_date is null or end_date is null) then
           start_date = date_trunc('month',now())-interval '1 month')::date ;
            end_date = date_trunc('month'now())-interval '1 day')::date;
        end if;
    
    
END;
$bach$ language plpgsql;

but i get syntax error SQL errir [42704] ERROR: unrecognized exception condition "is null" is there any other way to check if in parameter date is null and replace it with default date


Solution

  • You have many incorrect syntaxes here.

    Sample for you, this is working:

    CREATE OR REPLACE FUNCTION test(start_date date)
     RETURNS date
     LANGUAGE plpgsql
    AS $function$
    begin
        
        if (start_date is null) then 
        start_date = date_trunc('month', now() - interval '1 month')::date;
        end if; 
    
        return start_date;
        
    end ;
    $function$
    ;
    
    select test(null)
    
    -- Result: 
    2022-11-01