9

How can I concatenate two psql (PostgreSQL client) variables? I want to generate an absolute path by concatenating a directory path variable and a filename variable.

I've tried this:

\set path '/tmp/'
\set file 'foo'
\echo :path:file

But psql puts a space between the path and the file, and outputs:

/tmp/ foo

3 Answers 3

10
\set path '/tmp/'
\set file 'foo'
\set pf :path:file \echo :pf
/tmp/foo

Why does this work? I quote the manual here:

\set [ name [ value [ ... ] ] ]

Sets the internal variable name to value or, if more than one value is given, to the concatenation of all of them. [...]

Emphasis mine.

1
4

Try this:

\set path /tmp/
\set file foo
\qecho :path:file \o | sed s/\ //
/tmp/foo

\qecho writes to the query output channel (unlike \echo, which writes to standard output). \o | then redirects the output to the subsequent command.

0

It looks like you want either the || operator or the concat function:

http://www.postgresql.org/docs/9.1/static/functions-string.html

2
  • 1
    How do you use these with \echo? Jul 18, 2012 at 12:26
  • This answer refers to concatenation in SQL while the question is about psql (the terminal interface). Feb 4, 2013 at 20:20

Your Answer

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

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