vsql provides variable substitution features similar to common Linux command shells. Variables are simply name/value pairs, where the value can be any string of any length. To set variables, use the vsql meta-command
:\set
testdb=> \set foo bar
sets the variable foo
to the value bar
. To retrieve the content of the variable, precede the name with a colon and use it as the argument of any slash command:
testdb=> \echo :foo
bar
Note: The arguments of \set are subject to the same substitution rules as with other commands. For example, \set bar :foo is a valid way to copy a variable.
If you call \set
without a second argument, the variable is set, with an empty string as value. To unset (or delete) a variable, use the command \unset
.
vsql's internal variable names can consist of letters, numbers, and underscores in any order and any number. Some of these variables are treated specially by vsql. They indicate certain option settings that can be changed at run time by altering the value of the variable or represent some state of the application. Although you can use these variables for any other purpose, this is not recommended. By convention, all specially treated variables consist of all upper-case letters (and possibly numbers and underscores). To ensure maximum compatibility in the future, avoid using such variable names for your own purposes.
SQL Interpolation
An additional useful feature of vsql variables is that you can substitute ("interpolate") them into regular SQL statements. The syntax for this is again to prepend the variable name with a colon (:
).
testdb=> \set foo 'my_table'
testdb=> SELECT * FROM :foo;
would then query the table my_table
. The value of the variable is copied literally, so it can even contain unbalanced quotes or backslash commands. Make sure that it makes sense where you put it. Variable interpolation is not performed into quoted SQL entities.