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
< do whatever here>
END $$
but that makes me declare the variables each time I have a BEGIN / END block.
Best Answer
There are no global variables per se in Postgres. But we have "customized options" that can be streched for the puropose.
Persists for the duration of the session (not just transaction). Use with:
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:See:
There are a number of other workarounds, too: