Let's say I have a windows user environment variable SOME_STRING.

Is it possible to use its value in a PL/pgSQL function?

If not, do I need to use an untrusted language (like PL/pythonu) or can I use a trusted one?

I am on PG 9.2

2 Answers 2


You can not access a environment variable directly; but you can access a custom configuration setting and set that to a value from the environment at startup. For example, you can pass the follow startup option using PGOPTIONS:

PGOPTIONS="-c 'custom.some_string=${SOME_STRING}'"

Note: the dot (.) in the name is important.

Then retrieve the value using current_setting:

SELECT current_setting('custom.some_string');

(I have tried this on Linux and found it to be working, it should be the same for Windows, but may need some slight modification to cater for that particular platform.)

Custom parameters have been possible since postgresql version 8.0 with the use of custom_variable_classes (see 16.4.12. Customized Options) Since postgresql version 10.0, the use of custom_variable_classes is not necessary but the parameter name must still consist of two parts, separated by a ., first a variable class name, then the variable name. The class name should be unique across all loaded modules.

  • What postgresql version?
    – dmvianna
    Jul 4, 2022 at 7:26
  • @dmvianna, I've updated the answer with details for specific versions. TL;DR v8.0 or greater.
    – Corin
    Jul 5, 2022 at 12:32
  • 2
    I couldn’t do this in 14, but instead I was able to assign variables using psql -v variable_name=“$ENV_VARIABLE” and then using it within scripts as :variable_name.
    – dmvianna
    Jul 5, 2022 at 12:35
  • 1
    @dmvianna, that's fair, OP was asking about the use in PL/pgSQL function, which means the value would need to be set when the server starts. You appear to be using an envvar from the client's environment (i.e. psql), which is a little different. Having said this, I thought that the method I described should still be applicable 🤔
    – Corin
    Jul 5, 2022 at 12:56

To set a env variable in session level:

set db.beta = 'Stored in env variable';

(db.beta can be replaced with any string as desired but it should have dot(.) in-between)

To use env variable in your query:

create table neo(display text);

insert into neo values((SELECT current_setting('db.beta')));

To set env variable globally, put the variable in postgresql.conf file under CUSTOMIZED OPTIONS like below.

db.beta = 'Stored in env variable'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.