vsql provides variable substitution features similar to common Linux command shells. Variables are name/value pairs, where the value can be a string of any length. To set variables, use the vsql meta-command
\set. For example, the following statement sets the variable
fact to the value
=> \set fact dim
If you call
\set on a variable and supply no value, the variable is set to an empty string.
The arguments of
\set are subject to the same substitution rules as with other commands. For example,
\set dim :fact is a valid way to copy a variable.
To retrieve the content of a given variable, precede the name with a colon and use it as the argument of any slash command. For example:
=> \echo :fact dim
\set command returns all current variables and their values:
To unset (or delete) a variable, use the vsql meta-command
Variable Naming Conventions
vsql internal variable names can contain letters, numbers, and underscores in any order and any number. Some 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.
You can substitute ("interpolate") vsql variables into regular SQL statements. You do so by prepending the variable name with a colon (
:). For exaqmple, the following statements query the table
=> \set fact 'my_table' => SELECT * FROM :fact;
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. One exception applies: the contents of backquoted strings (
``) are passed to a system shell, and replaced with the shell's output. See Using Backquotes to Read System Variables below.
In vsql, the contents of backquotes are passed to the system shell to be interpreted (the same behavior as many UNIX shells). This is particularly useful in setting internal vsql variables, since you may want to access UNIX system variables (such as HOME or TMPDIR) rather than hard-code values.
For example, to set an internal variable to the full path for a file in your UNIX user directory, you can use backquotes to get the content of the system HOME variable, which is the full path to your user directory:
=> \set inputfile `echo $HOME`/myinput.txt=> \echo :inputfile /home/dbadmin/myinput.txt
The contents of the backquotes are replaced with the results of running the contents in a system shell interpreter. In this case, the
echo $HOME command returns the contents of the HOME system variable.