Declaring variable for a whole script I have a PostgreSQL 10 script for which I would like to declare variables once at the beginning and then use them throughout the script (with possible transactions).

I know I can do:

DO $$
DECLARE test float := 0.1 ;
BEGIN
    &lt; do whatever here&gt;
END $$


but that makes me declare the variables each time I have a BEGIN / END block.
There are no global variables per se in Postgres. But we have "customized options" that can be streched for the puropose.

SET myvars.test TO '0.1';


Persists for the duration of the session (not just transaction). Use with:

SELECT current_setting('myvars.test')::float;


Be aware that values are stored as text. So you may need to cast as demonstrated.

To avoid exceptions when referencing an unset variable and get NULL instead:

SELECT current_setting('myvars.test', true)::float;


See:


Assign the result of current_setting(&#39;the_setting&#39;) to a variable in PL/pgSQL


There are a number of other workarounds, too:


Is there a way to define a named constant in a PostgreSQL query?