How do I declare variables in pgAdmin

dagda1 picture dagda1 · May 9, 2014 · Viewed 24.9k times · Source

If I am in the psql terminal then I can declare and use a variable like this:

\set message_id soifsdaofisd.gmail.com;
select * from emails where message_id = ':message_id';

How can I do this in pgAdmin?

I get an error when ever I try this in pgAdmin:

ERROR: syntax error at or near "CALAdkA4YC0" LINE 3: set message_id soifsdaofisd.gmail.com.

Answer

Erwin Brandstetter picture Erwin Brandstetter · May 21, 2014

\set is a feature of psql (the interactive command line terminal) and not available in pgAdmin.

PostgreSQL does not normally use variables in plain SQL. You would use PL/pgSQL code in an anonymous block (DO statement) or in a function.

However, you can (ab)use customized options, for server-side "variables", independent the client in use:

SET foo.test = 'SELECT bar FROM baz';
SELECT current_setting('foo.test');

Details in this related answer:

And there is also (was) pgScript, a local scripting extension of the pgAdmin3 query tool, where you can use local variables, comparable to what you can do in psql. The manual:

You can run pgScript scripts by selecting Execute pgScript from the Query menu instead of Execute, or you press the Execute pgScript toolbar button, or you press the F6 function key.

But pgAdmin3 is unmaintained now, and pgAdmin4 does not include pgScript. Wasn't all that useful.