Postgresql – How to use value return by postgresSQL function in another query

postgresqlpostgresql-9.2

I am calling PostgreSQL function that returns me the text, How can I store this value in local variable and use the value/variable in another query. ?

Best Answer

It's not very clear what exactly you mean by a local variable - there is no such thing in SQL. In this case, just use the function in the place where you would put your variable (like a_horse_with_no_name suggested in his comment), like

SELECT important_thing FROM fancy_table WHERE it_thing_happened > now();

now() is a function, and illustrates the case nicely.

If you are about PL/pgSQL variables, you can do

[...]
my_timestamp := now();  -- not very meaningful IRL
[...]

Note that you can do this only inside a PL/pgSQL function or a DO block.

Last, if you mean a psql (that is, client-side) variable, you can use the \gset command:

test=# SELECT now() AS ts
test-# \gset i
test=# \echo :ts
2017-05-31 10:34:48.148068+02

Note that \gset is available from psql version 9.3 only.