First, I experimented the DEFAULT local variable value which has 2 as shown below:
CREATE FUNCTION my_func() RETURNS INTEGER AS $$
DECLARE
value INTEGER DEFAULT 2; -- Here
BEGIN
IF value = 2 THEN
value := 4;
RETURN value;
ELSE
value := 2;
RETURN value;
END IF;
END;
$$ LANGUAGE plpgsql;
Then, my_func() returned 4 twice without 4 and 2 alternately as shown below:
postgres=# SELECT my_func();
my_func
---------
4
(1 row)
postgres=# SELECT my_func();
my_func
---------
4
(1 row)
Second, I experimented the initialized local variable value which has 2 as shown below:
CREATE FUNCTION my_func() RETURNS INTEGER AS $$
DECLARE
value INTEGER := 2; -- Here
BEGIN
IF value = 2 THEN
value := 4;
RETURN value;
ELSE
value := 2;
RETURN value;
END IF;
END;
$$ LANGUAGE plpgsql;
Then, my_func() returned 4 twice without 4 and 2 alternately as shown below:
apple=# SELECT my_func();
my_func
---------
4
(1 row)
apple=# SELECT my_func();
my_func
---------
4
(1 row)
So, what is the difference between DEFAULT local variables and initialized local variables?
If your goal is to save a value, save it to a table. To persist it for the duration of a session, make it a
temptable. For transaction,temp...on commit drop.You can also use custom parameters and alter them from inside the function.
Otherwise, your
valuevariable lives only for the duration of the function and it's reinitialised individually for each call.Demo at db<>fiddle