PostgreSQL Functions – Set Default Values and Argument Dependencies

default valuefunctionspostgresql

I would like to write a function with two arguments, which would have dependency. Something like this:

    CREATE OR REPLACE FUNCTION years_compare(
        IN year1 integer DEFAULT date_part('year'::text, ('now'::text)::date),
        IN year2 integer DEFAULT year1 - 1)

...

When I call a function years_compare(2019), the second argument would have a value 2018. But how can I write a default value for the second argument?

Best Answer

CREATE OR REPLACE FUNCTION years_compare( IN year1 integer DEFAULT NULL,
                                          IN year2 integer DEFAULT NULL )

    year1 = COALESCE(year1, date_part('year'::text, ('now'::text)::date));
    year2 = COALESCE(year2, year1 - 1);
-- ...