2 doc/src/sgml/ref/psql-ref.sgml
3 PostgreSQL documentation
6 <refentry id="app-psql">
7 <indexterm zone="app-psql">
8 <primary>psql</primary>
12 <refentrytitle><application>psql</application></refentrytitle>
13 <manvolnum>1</manvolnum>
14 <refmiscinfo>Application</refmiscinfo>
18 <refname><application>psql</application></refname>
20 <productname>PostgreSQL</productname> interactive terminal
26 <command>psql</command>
27 <arg rep="repeat"><replaceable class="parameter">option</replaceable></arg>
28 <arg choice="opt"><replaceable class="parameter">dbname</replaceable>
29 <arg choice="opt"><replaceable class="parameter">username</replaceable></arg></arg>
34 <title>Description</title>
37 <application>psql</application> is a terminal-based front-end to
38 <productname>PostgreSQL</productname>. It enables you to type in
39 queries interactively, issue them to
40 <productname>PostgreSQL</productname>, and see the query results.
41 Alternatively, input can be from a file or from command line
42 arguments. In addition, <application>psql</application> provides a
43 number of meta-commands and various shell-like features to
44 facilitate writing scripts and automating a wide variety of tasks.
48 <refsect1 id="r1-app-psql-3">
49 <title>Options</title>
53 <term><option>-a</option></term>
54 <term><option>--echo-all</option></term>
57 Print all nonempty input lines to standard output as they are read.
58 (This does not apply to lines read interactively.) This is
59 equivalent to setting the variable <varname>ECHO</varname> to
60 <literal>all</literal>.
66 <term><option>-A</option></term>
67 <term><option>--no-align</option></term>
70 Switches to unaligned output mode. (The default output mode is
71 <literal>aligned</literal>.) This is equivalent to
72 <command>\pset format unaligned</command>.
78 <term><option>-b</option></term>
79 <term><option>--echo-errors</option></term>
82 Print failed SQL commands to standard error output. This is
83 equivalent to setting the variable <varname>ECHO</varname> to
84 <literal>errors</literal>.
90 <term><option>-c <replaceable class="parameter">command</replaceable></option></term>
91 <term><option>--command=<replaceable class="parameter">command</replaceable></option></term>
94 Specifies that <application>psql</application> is to execute the given
95 command string, <replaceable class="parameter">command</replaceable>.
96 This option can be repeated and combined in any order with
97 the <option>-f</option> option. When either <option>-c</option>
98 or <option>-f</option> is specified, <application>psql</application>
99 does not read commands from standard input; instead it terminates
100 after processing all the <option>-c</option> and <option>-f</option>
104 <replaceable class="parameter">command</replaceable> must be either
105 a command string that is completely parsable by the server (i.e.,
106 it contains no <application>psql</application>-specific features),
107 or a single backslash command. Thus you cannot mix
108 <acronym>SQL</acronym> and <application>psql</application>
109 meta-commands within a <option>-c</option> option. To achieve that,
110 you could use repeated <option>-c</option> options or pipe the string
111 into <application>psql</application>, for example:
113 psql -c '\x' -c 'SELECT * FROM foo;'
117 echo '\x \\ SELECT * FROM foo;' | psql
119 (<literal>\\</literal> is the separator meta-command.)
122 Each <acronym>SQL</acronym> command string passed
123 to <option>-c</option> is sent to the server as a single request.
124 Because of this, the server executes it as a single transaction even
125 if the string contains multiple <acronym>SQL</acronym> commands,
126 unless there are explicit <command>BEGIN</command>/<command>COMMIT</command>
127 commands included in the string to divide it into multiple
128 transactions. (See <xref linkend="protocol-flow-multi-statement"/>
129 for more details about how the server handles multi-query strings.)
130 Also, <application>psql</application> only prints the
131 result of the last <acronym>SQL</acronym> command in the string.
132 This is different from the behavior when the same string is read from
133 a file or fed to <application>psql</application>'s standard input,
134 because then <application>psql</application> sends
135 each <acronym>SQL</acronym> command separately.
138 Because of this behavior, putting more than one SQL command in a
139 single <option>-c</option> string often has unexpected results.
140 It's better to use repeated <option>-c</option> commands or feed
141 multiple commands to <application>psql</application>'s standard input,
142 either using <application>echo</application> as illustrated above, or
143 via a shell here-document, for example:
155 <term><option>--csv</option></term>
158 Switches to <acronym>CSV</acronym> (Comma-Separated Values) output
159 mode. This is equivalent to <command>\pset format csv</command>.
165 <term><option>-d <replaceable class="parameter">dbname</replaceable></option></term>
166 <term><option>--dbname=<replaceable class="parameter">dbname</replaceable></option></term>
169 Specifies the name of the database to connect to. This is
170 equivalent to specifying <replaceable
171 class="parameter">dbname</replaceable> as the first non-option
172 argument on the command line.
175 If this parameter contains an <symbol>=</symbol> sign or starts
176 with a valid <acronym>URI</acronym> prefix
177 (<literal>postgresql://</literal>
178 or <literal>postgres://</literal>), it is treated as a
179 <parameter>conninfo</parameter> string. See <xref
180 linkend="libpq-connstring"/> for more information.
186 <term><option>-e</option></term>
187 <term><option>--echo-queries</option></term>
190 Copy all SQL commands sent to the server to standard output as well.
192 to setting the variable <varname>ECHO</varname> to
193 <literal>queries</literal>.
199 <term><option>-E</option></term>
200 <term><option>--echo-hidden</option></term>
203 Echo the actual queries generated by <command>\d</command> and other backslash
204 commands. You can use this to study <application>psql</application>'s
205 internal operations. This is equivalent to
206 setting the variable <varname>ECHO_HIDDEN</varname> to <literal>on</literal>.
212 <term><option>-f <replaceable class="parameter">filename</replaceable></option></term>
213 <term><option>--file=<replaceable class="parameter">filename</replaceable></option></term>
216 Read commands from the
217 file <replaceable class="parameter">filename</replaceable>,
218 rather than standard input.
219 This option can be repeated and combined in any order with
220 the <option>-c</option> option. When either <option>-c</option>
221 or <option>-f</option> is specified, <application>psql</application>
222 does not read commands from standard input; instead it terminates
223 after processing all the <option>-c</option> and <option>-f</option>
225 Except for that, this option is largely equivalent to the
226 meta-command <command>\i</command>.
230 If <replaceable>filename</replaceable> is <literal>-</literal>
231 (hyphen), then standard input is read until an EOF indication
232 or <command>\q</command> meta-command. This can be used to intersperse
233 interactive input with input from files. Note however that Readline
234 is not used in this case (much as if <option>-n</option> had been
239 Using this option is subtly different from writing <literal>psql
241 class="parameter">filename</replaceable></literal>. In general,
242 both will do what you expect, but using <literal>-f</literal>
243 enables some nice features such as error messages with line
244 numbers. There is also a slight chance that using this option will
245 reduce the start-up overhead. On the other hand, the variant using
246 the shell's input redirection is (in theory) guaranteed to yield
247 exactly the same output you would have received had you entered
254 <term><option>-F <replaceable class="parameter">separator</replaceable></option></term>
255 <term><option>--field-separator=<replaceable class="parameter">separator</replaceable></option></term>
258 Use <replaceable class="parameter">separator</replaceable> as the
259 field separator for unaligned output. This is equivalent to
260 <command>\pset fieldsep</command> or <command>\f</command>.
266 <term><option>-h <replaceable class="parameter">hostname</replaceable></option></term>
267 <term><option>--host=<replaceable class="parameter">hostname</replaceable></option></term>
270 Specifies the host name of the machine on which the
271 server is running. If the value begins
272 with a slash, it is used as the directory for the Unix-domain
279 <term><option>-H</option></term>
280 <term><option>--html</option></term>
283 Switches to <acronym>HTML</acronym> output mode. This is
284 equivalent to <command>\pset format html</command> or the
285 <command>\H</command> command.
291 <term><option>-l</option></term>
292 <term><option>--list</option></term>
295 List all available databases, then exit. Other non-connection
296 options are ignored. This is similar to the meta-command
297 <command>\list</command>.
301 When this option is used, <application>psql</application> will connect
302 to the database <literal>postgres</literal>, unless a different database
303 is named on the command line (option <option>-d</option> or non-option
304 argument, possibly via a service entry, but not via an environment
311 <term><option>-L <replaceable class="parameter">filename</replaceable></option></term>
312 <term><option>--log-file=<replaceable class="parameter">filename</replaceable></option></term>
315 Write all query output into file <replaceable
316 class="parameter">filename</replaceable>, in addition to the
317 normal output destination.
323 <term><option>-n</option></term>
324 <term><option>--no-readline</option></term>
327 Do not use <application>Readline</application> for line editing and do
328 not use the command history.
329 This can be useful to turn off tab expansion when cutting and pasting.
335 <term><option>-o <replaceable class="parameter">filename</replaceable></option></term>
336 <term><option>--output=<replaceable class="parameter">filename</replaceable></option></term>
339 Put all query output into file <replaceable
340 class="parameter">filename</replaceable>. This is equivalent to
341 the command <command>\o</command>.
347 <term><option>-p <replaceable class="parameter">port</replaceable></option></term>
348 <term><option>--port=<replaceable class="parameter">port</replaceable></option></term>
351 Specifies the TCP port or the local Unix-domain
352 socket file extension on which the server is listening for
353 connections. Defaults to the value of the <envar>PGPORT</envar>
354 environment variable or, if not set, to the port specified at
355 compile time, usually 5432.
361 <term><option>-P <replaceable class="parameter">assignment</replaceable></option></term>
362 <term><option>--pset=<replaceable class="parameter">assignment</replaceable></option></term>
365 Specifies printing options, in the style of
366 <command>\pset</command>. Note that here you
367 have to separate name and value with an equal sign instead of a
368 space. For example, to set the output format to <application>LaTeX</application>, you could write
369 <literal>-P format=latex</literal>.
375 <term><option>-q</option></term>
376 <term><option>--quiet</option></term>
379 Specifies that <application>psql</application> should do its work
380 quietly. By default, it prints welcome messages and various
381 informational output. If this option is used, none of this
382 happens. This is useful with the <option>-c</option> option.
383 This is equivalent to setting the variable <varname>QUIET</varname>
384 to <literal>on</literal>.
390 <term><option>-R <replaceable class="parameter">separator</replaceable></option></term>
391 <term><option>--record-separator=<replaceable class="parameter">separator</replaceable></option></term>
394 Use <replaceable class="parameter">separator</replaceable> as the
395 record separator for unaligned output. This is equivalent to
396 <command>\pset recordsep</command>.
402 <term><option>-s</option></term>
403 <term><option>--single-step</option></term>
406 Run in single-step mode. That means the user is prompted before
407 each command is sent to the server, with the option to cancel
408 execution as well. Use this to debug scripts.
414 <term><option>-S</option></term>
415 <term><option>--single-line</option></term>
418 Runs in single-line mode where a newline terminates an SQL command, as a
424 This mode is provided for those who insist on it, but you are not
425 necessarily encouraged to use it. In particular, if you mix
426 <acronym>SQL</acronym> and meta-commands on a line the order of
427 execution might not always be clear to the inexperienced user.
434 <term><option>-t</option></term>
435 <term><option>--tuples-only</option></term>
438 Turn off printing of column names and result row count footers,
439 etc. This is equivalent to <command>\t</command> or
440 <command>\pset tuples_only</command>.
446 <term><option>-T <replaceable class="parameter">table_options</replaceable></option></term>
447 <term><option>--table-attr=<replaceable class="parameter">table_options</replaceable></option></term>
450 Specifies options to be placed within the
451 <acronym>HTML</acronym> <sgmltag>table</sgmltag> tag. See
452 <command>\pset tableattr</command> for details.
458 <term><option>-U <replaceable class="parameter">username</replaceable></option></term>
459 <term><option>--username=<replaceable class="parameter">username</replaceable></option></term>
462 Connect to the database as the user <replaceable
463 class="parameter">username</replaceable> instead of the default.
464 (You must have permission to do so, of course.)
470 <term><option>-v <replaceable class="parameter">assignment</replaceable></option></term>
471 <term><option>--set=<replaceable class="parameter">assignment</replaceable></option></term>
472 <term><option>--variable=<replaceable class="parameter">assignment</replaceable></option></term>
475 Perform a variable assignment, like the <command>\set</command>
476 meta-command. Note that you must separate name and value, if
477 any, by an equal sign on the command line. To unset a variable,
478 leave off the equal sign. To set a variable with an empty value,
479 use the equal sign but leave off the value. These assignments are
480 done during command line processing, so variables that reflect
481 connection state will get overwritten later.
487 <term><option>-V</option></term>
488 <term><option>--version</option></term>
491 Print the <application>psql</application> version and exit.
497 <term><option>-w</option></term>
498 <term><option>--no-password</option></term>
501 Never issue a password prompt. If the server requires password
502 authentication and a password is not available by other means
503 such as a <filename>.pgpass</filename> file, the connection
504 attempt will fail. This option can be useful in batch jobs and
505 scripts where no user is present to enter a password.
509 Note that this option will remain set for the entire session,
510 and so it affects uses of the meta-command
511 <command>\connect</command> as well as the initial connection attempt.
517 <term><option>-W</option></term>
518 <term><option>--password</option></term>
521 Force <application>psql</application> to prompt for a
522 password before connecting to a database.
526 This option is never essential, since <application>psql</application>
527 will automatically prompt for a password if the server demands
528 password authentication. However, <application>psql</application>
529 will waste a connection attempt finding out that the server wants a
530 password. In some cases it is worth typing <option>-W</option> to avoid
531 the extra connection attempt.
535 Note that this option will remain set for the entire session,
536 and so it affects uses of the meta-command
537 <command>\connect</command> as well as the initial connection attempt.
543 <term><option>-x</option></term>
544 <term><option>--expanded</option></term>
547 Turn on the expanded table formatting mode. This is equivalent to
548 <command>\x</command> or <command>\pset expanded</command>.
554 <term><option>-X,</option></term>
555 <term><option>--no-psqlrc</option></term>
558 Do not read the start-up file (neither the system-wide
559 <filename>psqlrc</filename> file nor the user's
560 <filename>~/.psqlrc</filename> file).
566 <term><option>-z</option></term>
567 <term><option>--field-separator-zero</option></term>
570 Set the field separator for unaligned output to a zero byte. This is
571 equivalent to <command>\pset fieldsep_zero</command>.
577 <term><option>-0</option></term>
578 <term><option>--record-separator-zero</option></term>
581 Set the record separator for unaligned output to a zero byte. This is
582 useful for interfacing, for example, with <literal>xargs -0</literal>.
583 This is equivalent to <command>\pset recordsep_zero</command>.
589 <term><option>-1</option></term>
590 <term><option>--single-transaction</option></term>
593 This option can only be used in combination with one or more
594 <option>-c</option> and/or <option>-f</option> options. It causes
595 <application>psql</application> to issue a <command>BEGIN</command> command
596 before the first such option and a <command>COMMIT</command> command after
597 the last one, thereby wrapping all the commands into a single
598 transaction. This ensures that either all the commands complete
599 successfully, or no changes are applied.
603 If the commands themselves
604 contain <command>BEGIN</command>, <command>COMMIT</command>,
605 or <command>ROLLBACK</command>, this option will not have the desired
606 effects. Also, if an individual command cannot be executed inside a
607 transaction block, specifying this option will cause the whole
614 <term><option>-?</option></term>
615 <term><option>--help[=<replaceable class="parameter">topic</replaceable>]</option></term>
618 Show help about <application>psql</application> and exit. The optional
619 <replaceable class="parameter">topic</replaceable> parameter (defaulting
620 to <literal>options</literal>) selects which part of <application>psql</application> is
621 explained: <literal>commands</literal> describes <application>psql</application>'s
622 backslash commands; <literal>options</literal> describes the command-line
623 options that can be passed to <application>psql</application>;
624 and <literal>variables</literal> shows help about <application>psql</application> configuration
635 <title>Exit Status</title>
638 <application>psql</application> returns 0 to the shell if it
639 finished normally, 1 if a fatal error of its own occurs (e.g. out of memory,
640 file not found), 2 if the connection to the server went bad
641 and the session was not interactive, and 3 if an error occurred in a
642 script and the variable <varname>ON_ERROR_STOP</varname> was set.
650 <refsect2 id="r2-app-psql-connecting">
651 <title>Connecting to a Database</title>
654 <application>psql</application> is a regular
655 <productname>PostgreSQL</productname> client application. In order
656 to connect to a database you need to know the name of your target
657 database, the host name and port number of the server, and what user
658 name you want to connect as. <application>psql</application> can be
659 told about those parameters via command line options, namely
660 <option>-d</option>, <option>-h</option>, <option>-p</option>, and
661 <option>-U</option> respectively. If an argument is found that does
662 not belong to any option it will be interpreted as the database name
663 (or the user name, if the database name is already given). Not all
664 of these options are required; there are useful defaults. If you omit the host
665 name, <application>psql</application> will connect via a Unix-domain socket
666 to a server on the local host, or via TCP/IP to <literal>localhost</literal> on
667 machines that don't have Unix-domain sockets. The default port number is
668 determined at compile time.
669 Since the database server uses the same default, you will not have
670 to specify the port in most cases. The default user name is your
671 operating-system user name, as is the default database name.
673 just connect to any database under any user name. Your database
674 administrator should have informed you about your access rights.
678 When the defaults aren't quite right, you can save yourself
679 some typing by setting the environment variables
680 <envar>PGDATABASE</envar>, <envar>PGHOST</envar>,
681 <envar>PGPORT</envar> and/or <envar>PGUSER</envar> to appropriate
682 values. (For additional environment variables, see <xref
683 linkend="libpq-envars"/>.) It is also convenient to have a
684 <filename>~/.pgpass</filename> file to avoid regularly having to type in
685 passwords. See <xref linkend="libpq-pgpass"/> for more information.
689 An alternative way to specify connection parameters is in a
690 <parameter>conninfo</parameter> string or
691 a <acronym>URI</acronym>, which is used instead of a database
692 name. This mechanism give you very wide control over the
693 connection. For example:
695 $ <userinput>psql "service=myservice sslmode=require"</userinput>
696 $ <userinput>psql postgresql://dbmaster:5433/mydb?sslmode=require</userinput>
698 This way you can also use <acronym>LDAP</acronym> for connection
699 parameter lookup as described in <xref linkend="libpq-ldap"/>.
700 See <xref linkend="libpq-paramkeywords"/> for more information on all the
701 available connection options.
705 If the connection could not be made for any reason (e.g., insufficient
706 privileges, server is not running on the targeted host, etc.),
707 <application>psql</application> will return an error and terminate.
711 If both standard input and standard output are a
712 terminal, then <application>psql</application> sets the client
713 encoding to <quote>auto</quote>, which will detect the
714 appropriate client encoding from the locale settings
715 (<envar>LC_CTYPE</envar> environment variable on Unix systems).
716 If this doesn't work out as expected, the client encoding can be
717 overridden using the environment
718 variable <envar>PGCLIENTENCODING</envar>.
722 <refsect2 id="r2-app-psql-4">
723 <title>Entering SQL Commands</title>
726 In normal operation, <application>psql</application> provides a
727 prompt with the name of the database to which
728 <application>psql</application> is currently connected, followed by
729 the string <literal>=></literal>. For example:
731 $ <userinput>psql testdb</userinput>
733 Type "help" for help.
740 At the prompt, the user can type in <acronym>SQL</acronym> commands.
741 Ordinarily, input lines are sent to the server when a
742 command-terminating semicolon is reached. An end of line does not
743 terminate a command. Thus commands can be spread over several lines for
744 clarity. If the command was sent and executed without error, the results
745 of the command are displayed on the screen.
749 If untrusted users have access to a database that has not adopted a
750 <link linkend="ddl-schemas-patterns">secure schema usage pattern</link>,
751 begin your session by removing publicly-writable schemas
752 from <varname>search_path</varname>. One can
753 add <literal>options=-csearch_path=</literal> to the connection string or
754 issue <literal>SELECT pg_catalog.set_config('search_path', '',
755 false)</literal> before other SQL commands. This consideration is not
756 specific to <application>psql</application>; it applies to every interface
757 for executing arbitrary SQL commands.
761 Whenever a command is executed, <application>psql</application> also polls
762 for asynchronous notification events generated by
763 <xref linkend="sql-listen"/> and
764 <xref linkend="sql-notify"/>.
768 While C-style block comments are passed to the server for
769 processing and removal, SQL-standard comments are removed by
770 <application>psql</application>.
774 <refsect2 id="app-psql-meta-commands">
775 <title>Meta-Commands</title>
778 Anything you enter in <application>psql</application> that begins
779 with an unquoted backslash is a <application>psql</application>
780 meta-command that is processed by <application>psql</application>
781 itself. These commands make
782 <application>psql</application> more useful for administration or
783 scripting. Meta-commands are often called slash or backslash commands.
787 The format of a <application>psql</application> command is the backslash,
788 followed immediately by a command verb, then any arguments. The arguments
789 are separated from the command verb and each other by any number of
790 whitespace characters.
794 To include whitespace in an argument you can quote it with
795 single quotes. To include a single quote in an argument,
796 write two single quotes within single-quoted text.
797 Anything contained in single quotes is
798 furthermore subject to C-like substitutions for
799 <literal>\n</literal> (new line), <literal>\t</literal> (tab),
800 <literal>\b</literal> (backspace), <literal>\r</literal> (carriage return),
801 <literal>\f</literal> (form feed),
802 <literal>\</literal><replaceable>digits</replaceable> (octal), and
803 <literal>\x</literal><replaceable>digits</replaceable> (hexadecimal).
804 A backslash preceding any other character within single-quoted text
805 quotes that single character, whatever it is.
809 If an unquoted colon (<literal>:</literal>) followed by a
810 <application>psql</application> variable name appears within an argument, it is
811 replaced by the variable's value, as described in <xref
812 linkend="app-psql-interpolation" endterm="app-psql-interpolation-title"/>.
813 The forms <literal>:'<replaceable>variable_name</replaceable>'</literal> and
814 <literal>:"<replaceable>variable_name</replaceable>"</literal> described there
816 The <literal>:{?<replaceable>variable_name</replaceable>}</literal> syntax allows
817 testing whether a variable is defined. It is substituted by
819 Escaping the colon with a backslash protects it from substitution.
823 Within an argument, text that is enclosed in backquotes
824 (<literal>`</literal>) is taken as a command line that is passed to the
825 shell. The output of the command (with any trailing newline removed)
826 replaces the backquoted text. Within the text enclosed in backquotes,
827 no special quoting or other processing occurs, except that appearances
828 of <literal>:<replaceable>variable_name</replaceable></literal> where
829 <replaceable>variable_name</replaceable> is a <application>psql</application> variable name
830 are replaced by the variable's value. Also, appearances of
831 <literal>:'<replaceable>variable_name</replaceable>'</literal> are replaced by the
832 variable's value suitably quoted to become a single shell command
833 argument. (The latter form is almost always preferable, unless you are
834 very sure of what is in the variable.) Because carriage return and line
835 feed characters cannot be safely quoted on all platforms, the
836 <literal>:'<replaceable>variable_name</replaceable>'</literal> form prints an
837 error message and does not substitute the variable value when such
838 characters appear in the value.
842 Some commands take an <acronym>SQL</acronym> identifier (such as a
843 table name) as argument. These arguments follow the syntax rules
844 of <acronym>SQL</acronym>: Unquoted letters are forced to
845 lowercase, while double quotes (<literal>"</literal>) protect letters
846 from case conversion and allow incorporation of whitespace into
847 the identifier. Within double quotes, paired double quotes reduce
848 to a single double quote in the resulting name. For example,
849 <literal>FOO"BAR"BAZ</literal> is interpreted as <literal>fooBARbaz</literal>,
850 and <literal>"A weird"" name"</literal> becomes <literal>A weird"
855 Parsing for arguments stops at the end of the line, or when another
856 unquoted backslash is found. An unquoted backslash
857 is taken as the beginning of a new meta-command. The special
858 sequence <literal>\\</literal> (two backslashes) marks the end of
859 arguments and continues parsing <acronym>SQL</acronym> commands, if
860 any. That way <acronym>SQL</acronym> and
861 <application>psql</application> commands can be freely mixed on a
862 line. But in any case, the arguments of a meta-command cannot
863 continue beyond the end of the line.
867 Many of the meta-commands act on the <firstterm>current query buffer</firstterm>.
868 This is simply a buffer holding whatever SQL command text has been typed
869 but not yet sent to the server for execution. This will include previous
870 input lines as well as any text appearing before the meta-command on the
875 The following meta-commands are defined:
879 <term><literal>\a</literal></term>
882 If the current table output format is unaligned, it is switched to aligned.
883 If it is not unaligned, it is set to unaligned. This command is
884 kept for backwards compatibility. See <command>\pset</command> for a
885 more general solution.
891 <term><literal>\c</literal> or <literal>\connect [ -reuse-previous=<replaceable class="parameter">on|off</replaceable> ] [ <replaceable class="parameter">dbname</replaceable> [ <replaceable class="parameter">username</replaceable> ] [ <replaceable class="parameter">host</replaceable> ] [ <replaceable class="parameter">port</replaceable> ] | <replaceable class="parameter">conninfo</replaceable> ]</literal></term>
894 Establishes a new connection to a <productname>PostgreSQL</productname>
895 server. The connection parameters to use can be specified either
896 using a positional syntax, or using <replaceable>conninfo</replaceable> connection
897 strings as detailed in <xref linkend="libpq-connstring"/>.
901 Where the command omits database name, user, host, or port, the new
902 connection can reuse values from the previous connection. By default,
903 values from the previous connection are reused except when processing
904 a <replaceable>conninfo</replaceable> string. Passing a first argument
905 of <literal>-reuse-previous=on</literal>
906 or <literal>-reuse-previous=off</literal> overrides that default.
907 When the command neither specifies nor reuses a particular parameter,
908 the <application>libpq</application> default is used. Specifying any
909 of <replaceable class="parameter">dbname</replaceable>,
910 <replaceable class="parameter">username</replaceable>,
911 <replaceable class="parameter">host</replaceable> or
912 <replaceable class="parameter">port</replaceable>
913 as <literal>-</literal> is equivalent to omitting that parameter.
917 If the new connection is successfully made, the previous
918 connection is closed.
919 If the connection attempt failed (wrong user name, access
920 denied, etc.), the previous connection will only be kept if
921 <application>psql</application> is in interactive mode. When
922 executing a non-interactive script, processing will
923 immediately stop with an error. This distinction was chosen as
924 a user convenience against typos on the one hand, and a safety
925 mechanism that scripts are not accidentally acting on the
926 wrong database on the other hand.
933 => \c mydb myuser host.dom 6432
935 => \c "host=localhost port=5432 dbname=mydb connect_timeout=10 sslmode=disable"
936 => \c postgresql://tom@localhost/mydb?application_name=myapp
942 <term><literal>\C [ <replaceable class="parameter">title</replaceable> ]</literal></term>
945 Sets the title of any tables being printed as the result of a
946 query or unset any such title. This command is equivalent to
947 <literal>\pset title <replaceable
948 class="parameter">title</replaceable></literal>. (The name of
949 this command derives from <quote>caption</quote>, as it was
950 previously only used to set the caption in an
951 <acronym>HTML</acronym> table.)
957 <term><literal>\cd [ <replaceable>directory</replaceable> ]</literal></term>
960 Changes the current working directory to
961 <replaceable>directory</replaceable>. Without argument, changes
962 to the current user's home directory.
967 To print your current working directory, use <literal>\! pwd</literal>.
974 <term><literal>\conninfo</literal></term>
977 Outputs information about the current database connection.
982 <varlistentry id="app-psql-meta-commands-copy">
983 <term><literal>\copy { <replaceable class="parameter">table</replaceable> [ ( <replaceable class="parameter">column_list</replaceable> ) ] | ( <replaceable class="parameter">query</replaceable> ) }
984 { <literal>from</literal> | <literal>to</literal> }
985 { <replaceable class="parameter">'filename'</replaceable> | program <replaceable class="parameter">'command'</replaceable> | stdin | stdout | pstdin | pstdout }
986 [ [ with ] ( <replaceable class="parameter">option</replaceable> [, ...] ) ]</literal></term>
990 Performs a frontend (client) copy. This is an operation that
991 runs an <acronym>SQL</acronym> <xref linkend="sql-copy"/>
992 command, but instead of the server
993 reading or writing the specified file,
994 <application>psql</application> reads or writes the file and
995 routes the data between the server and the local file system.
996 This means that file accessibility and privileges are those of
997 the local user, not the server, and no SQL superuser
998 privileges are required.
1002 When <literal>program</literal> is specified,
1003 <replaceable class="parameter">command</replaceable> is
1004 executed by <application>psql</application> and the data passed from
1005 or to <replaceable class="parameter">command</replaceable> is
1006 routed between the server and the client.
1007 Again, the execution privileges are those of
1008 the local user, not the server, and no SQL superuser
1009 privileges are required.
1013 For <literal>\copy ... from stdin</literal>, data rows are read from the same
1014 source that issued the command, continuing until <literal>\.</literal>
1015 is read or the stream reaches <acronym>EOF</acronym>. This option is useful
1016 for populating tables in-line within a SQL script file.
1017 For <literal>\copy ... to stdout</literal>, output is sent to the same place
1018 as <application>psql</application> command output, and
1019 the <literal>COPY <replaceable>count</replaceable></literal> command status is
1020 not printed (since it might be confused with a data row).
1021 To read/write <application>psql</application>'s standard input or
1022 output regardless of the current command source or <literal>\o</literal>
1023 option, write <literal>from pstdin</literal> or <literal>to pstdout</literal>.
1027 The syntax of this command is similar to that of the
1028 <acronym>SQL</acronym> <xref linkend="sql-copy"/>
1029 command. All options other than the data source/destination are
1030 as specified for <xref linkend="sql-copy"/>.
1031 Because of this, special parsing rules apply to the <command>\copy</command>
1032 meta-command. Unlike most other meta-commands, the entire remainder
1033 of the line is always taken to be the arguments of <command>\copy</command>,
1034 and neither variable interpolation nor backquote expansion are
1035 performed in the arguments.
1040 Another way to obtain the same result as <literal>\copy
1041 ... to</literal> is to use the <acronym>SQL</acronym> <literal>COPY
1042 ... TO STDOUT</literal> command and terminate it
1043 with <literal>\g <replaceable>filename</replaceable></literal>
1044 or <literal>\g |<replaceable>program</replaceable></literal>.
1045 Unlike <literal>\copy</literal>, this method allows the command to
1046 span multiple lines; also, variable interpolation and backquote
1047 expansion can be used.
1053 These operations are not as efficient as the <acronym>SQL</acronym>
1054 <command>COPY</command> command with a file or program data source or
1055 destination, because all data must pass through the client/server
1056 connection. For large amounts of data the <acronym>SQL</acronym>
1057 command might be preferable.
1065 <term><literal>\copyright</literal></term>
1068 Shows the copyright and distribution terms of
1069 <productname>PostgreSQL</productname>.
1075 <varlistentry id="app-psql-meta-commands-crosstabview">
1076 <term><literal>\crosstabview [
1077 <replaceable class="parameter">colV</replaceable>
1078 [ <replaceable class="parameter">colH</replaceable>
1079 [ <replaceable class="parameter">colD</replaceable>
1080 [ <replaceable class="parameter">sortcolH</replaceable>
1081 ] ] ] ] </literal></term>
1084 Executes the current query buffer (like <literal>\g</literal>) and
1085 shows the results in a crosstab grid.
1086 The query must return at least three columns.
1087 The output column identified by <replaceable class="parameter">colV</replaceable>
1088 becomes a vertical header and the output column identified by
1089 <replaceable class="parameter">colH</replaceable>
1090 becomes a horizontal header.
1091 <replaceable class="parameter">colD</replaceable> identifies
1092 the output column to display within the grid.
1093 <replaceable class="parameter">sortcolH</replaceable> identifies
1094 an optional sort column for the horizontal header.
1098 Each column specification can be a column number (starting at 1) or
1099 a column name. The usual SQL case folding and quoting rules apply to
1100 column names. If omitted,
1101 <replaceable class="parameter">colV</replaceable> is taken as column 1
1102 and <replaceable class="parameter">colH</replaceable> as column 2.
1103 <replaceable class="parameter">colH</replaceable> must differ from
1104 <replaceable class="parameter">colV</replaceable>.
1105 If <replaceable class="parameter">colD</replaceable> is not
1106 specified, then there must be exactly three columns in the query
1107 result, and the column that is neither
1108 <replaceable class="parameter">colV</replaceable> nor
1109 <replaceable class="parameter">colH</replaceable>
1110 is taken to be <replaceable class="parameter">colD</replaceable>.
1114 The vertical header, displayed as the leftmost column, contains the
1115 values found in column <replaceable class="parameter">colV</replaceable>, in the
1116 same order as in the query results, but with duplicates removed.
1120 The horizontal header, displayed as the first row, contains the values
1121 found in column <replaceable class="parameter">colH</replaceable>,
1122 with duplicates removed. By default, these appear in the same order
1123 as in the query results. But if the
1124 optional <replaceable class="parameter">sortcolH</replaceable> argument is given,
1125 it identifies a column whose values must be integer numbers, and the
1126 values from <replaceable class="parameter">colH</replaceable> will
1127 appear in the horizontal header sorted according to the
1128 corresponding <replaceable class="parameter">sortcolH</replaceable> values.
1132 Inside the crosstab grid, for each distinct value <literal>x</literal>
1133 of <replaceable class="parameter">colH</replaceable> and each distinct
1134 value <literal>y</literal>
1135 of <replaceable class="parameter">colV</replaceable>, the cell located
1136 at the intersection <literal>(x,y)</literal> contains the value of
1137 the <literal>colD</literal> column in the query result row for which
1138 the value of <replaceable class="parameter">colH</replaceable>
1139 is <literal>x</literal> and the value
1140 of <replaceable class="parameter">colV</replaceable>
1141 is <literal>y</literal>. If there is no such row, the cell is empty. If
1142 there are multiple such rows, an error is reported.
1149 <term><literal>\d[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1153 For each relation (table, view, materialized view, index, sequence,
1155 or composite type matching the
1156 <replaceable class="parameter">pattern</replaceable>, show all
1157 columns, their types, the tablespace (if not the default) and any
1158 special attributes such as <literal>NOT NULL</literal> or defaults.
1159 Associated indexes, constraints, rules, and triggers are
1160 also shown. For foreign tables, the associated foreign
1161 server is shown as well.
1162 (<quote>Matching the pattern</quote> is defined in
1163 <xref linkend="app-psql-patterns" endterm="app-psql-patterns-title"/>
1168 For some types of relation, <literal>\d</literal> shows additional information
1169 for each column: column values for sequences, indexed expressions for
1170 indexes, and foreign data wrapper options for foreign tables.
1174 The command form <literal>\d+</literal> is identical, except that
1175 more information is displayed: any comments associated with the
1176 columns of the table are shown, as is the presence of OIDs in the
1177 table, the view definition if the relation is a view, a non-default
1178 <link linkend="sql-createtable-replica-identity">replica
1179 identity</link> setting.
1183 By default, only user-created objects are shown; supply a
1184 pattern or the <literal>S</literal> modifier to include system
1190 If <command>\d</command> is used without a
1191 <replaceable class="parameter">pattern</replaceable> argument, it is
1192 equivalent to <command>\dtvmsE</command> which will show a list of
1193 all visible tables, views, materialized views, sequences and
1195 This is purely a convenience measure.
1202 <term><literal>\da[S] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1206 Lists aggregate functions, together with their
1207 return type and the data types they operate on. If <replaceable
1208 class="parameter">pattern</replaceable>
1209 is specified, only aggregates whose names match the pattern are shown.
1210 By default, only user-created objects are shown; supply a
1211 pattern or the <literal>S</literal> modifier to include system
1218 <term><literal>\dA[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1222 Lists access methods. If <replaceable
1223 class="parameter">pattern</replaceable> is specified, only access
1224 methods whose names match the pattern are shown. If
1225 <literal>+</literal> is appended to the command name, each access
1226 method is listed with its associated handler function and description.
1232 <term><literal>\db[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1236 Lists tablespaces. If <replaceable
1237 class="parameter">pattern</replaceable>
1238 is specified, only tablespaces whose names match the pattern are shown.
1239 If <literal>+</literal> is appended to the command name, each tablespace
1240 is listed with its associated options, on-disk size, permissions and
1248 <term><literal>\dc[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1251 Lists conversions between character-set encodings.
1252 If <replaceable class="parameter">pattern</replaceable>
1253 is specified, only conversions whose names match the pattern are
1255 By default, only user-created objects are shown; supply a
1256 pattern or the <literal>S</literal> modifier to include system
1258 If <literal>+</literal> is appended to the command name, each object
1259 is listed with its associated description.
1266 <term><literal>\dC[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1270 If <replaceable class="parameter">pattern</replaceable>
1271 is specified, only casts whose source or target types match the
1273 If <literal>+</literal> is appended to the command name, each object
1274 is listed with its associated description.
1281 <term><literal>\dd[S] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1284 Shows the descriptions of objects of type <literal>constraint</literal>,
1285 <literal>operator class</literal>, <literal>operator family</literal>,
1286 <literal>rule</literal>, and <literal>trigger</literal>. All
1287 other comments may be viewed by the respective backslash commands for
1291 <para><literal>\dd</literal> displays descriptions for objects matching the
1292 <replaceable class="parameter">pattern</replaceable>, or of visible
1293 objects of the appropriate type if no argument is given. But in either
1294 case, only objects that have a description are listed.
1295 By default, only user-created objects are shown; supply a
1296 pattern or the <literal>S</literal> modifier to include system
1301 Descriptions for objects can be created with the <xref
1302 linkend="sql-comment"/>
1303 <acronym>SQL</acronym> command.
1310 <term><literal>\dD[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1313 Lists domains. If <replaceable
1314 class="parameter">pattern</replaceable>
1315 is specified, only domains whose names match the pattern are shown.
1316 By default, only user-created objects are shown; supply a
1317 pattern or the <literal>S</literal> modifier to include system
1319 If <literal>+</literal> is appended to the command name, each object
1320 is listed with its associated permissions and description.
1327 <term><literal>\ddp [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1330 Lists default access privilege settings. An entry is shown for
1331 each role (and schema, if applicable) for which the default
1332 privilege settings have been changed from the built-in defaults.
1333 If <replaceable class="parameter">pattern</replaceable> is
1334 specified, only entries whose role name or schema name matches
1335 the pattern are listed.
1339 The <xref linkend="sql-alterdefaultprivileges"/> command is used to set
1340 default access privileges. The meaning of the
1341 privilege display is explained in
1342 <xref linkend="ddl-priv"/>.
1349 <term><literal>\dE[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1350 <term><literal>\di[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1351 <term><literal>\dm[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1352 <term><literal>\ds[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1353 <term><literal>\dt[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1354 <term><literal>\dv[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1358 In this group of commands, the letters <literal>E</literal>,
1359 <literal>i</literal>, <literal>m</literal>, <literal>s</literal>,
1360 <literal>t</literal>, and <literal>v</literal>
1361 stand for foreign table, index, materialized view, sequence, table, and view,
1363 You can specify any or all of
1364 these letters, in any order, to obtain a listing of objects
1365 of these types. For example, <literal>\dit</literal> lists indexes
1366 and tables. If <literal>+</literal> is
1367 appended to the command name, each object is listed with its
1368 physical size on disk and its associated description, if any.
1369 If <replaceable class="parameter">pattern</replaceable> is
1370 specified, only objects whose names match the pattern are listed.
1371 By default, only user-created objects are shown; supply a
1372 pattern or the <literal>S</literal> modifier to include system
1380 <term><literal>\des[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1383 Lists foreign servers (mnemonic: <quote>external
1385 If <replaceable class="parameter">pattern</replaceable> is
1386 specified, only those servers whose name matches the pattern
1387 are listed. If the form <literal>\des+</literal> is used, a
1388 full description of each server is shown, including the
1389 server's access privileges, type, version, options, and description.
1396 <term><literal>\det[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1399 Lists foreign tables (mnemonic: <quote>external tables</quote>).
1400 If <replaceable class="parameter">pattern</replaceable> is
1401 specified, only entries whose table name or schema name matches
1402 the pattern are listed. If the form <literal>\det+</literal>
1403 is used, generic options and the foreign table description
1411 <term><literal>\deu[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1414 Lists user mappings (mnemonic: <quote>external
1416 If <replaceable class="parameter">pattern</replaceable> is
1417 specified, only those mappings whose user names match the
1418 pattern are listed. If the form <literal>\deu+</literal> is
1419 used, additional information about each mapping is shown.
1424 <literal>\deu+</literal> might also display the user name and
1425 password of the remote user, so care should be taken not to
1434 <term><literal>\dew[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1437 Lists foreign-data wrappers (mnemonic: <quote>external
1439 If <replaceable class="parameter">pattern</replaceable> is
1440 specified, only those foreign-data wrappers whose name matches
1441 the pattern are listed. If the form <literal>\dew+</literal>
1442 is used, the access privileges, options, and description of the
1443 foreign-data wrapper are also shown.
1450 <term><literal>\df[anptwS+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1454 Lists functions, together with their result data types, argument data
1455 types, and function types, which are classified as <quote>agg</quote>
1456 (aggregate), <quote>normal</quote>, <quote>procedure</quote>, <quote>trigger</quote>, or <quote>window</quote>.
1457 To display only functions
1458 of specific type(s), add the corresponding letters <literal>a</literal>,
1459 <literal>n</literal>, <literal>p</literal>, <literal>t</literal>, or <literal>w</literal> to the command.
1461 class="parameter">pattern</replaceable> is specified, only
1462 functions whose names match the pattern are shown.
1463 By default, only user-created
1464 objects are shown; supply a pattern or the <literal>S</literal>
1465 modifier to include system objects.
1466 If the form <literal>\df+</literal> is used, additional information
1467 about each function is shown, including volatility,
1468 parallel safety, owner, security classification, access privileges,
1469 language, source code and description.
1474 To look up functions taking arguments or returning values of a specific
1475 data type, use your pager's search capability to scroll through the
1476 <literal>\df</literal> output.
1484 <term><literal>\dF[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1487 Lists text search configurations.
1488 If <replaceable class="parameter">pattern</replaceable> is specified,
1489 only configurations whose names match the pattern are shown.
1490 If the form <literal>\dF+</literal> is used, a full description of
1491 each configuration is shown, including the underlying text search
1492 parser and the dictionary list for each parser token type.
1498 <term><literal>\dFd[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1501 Lists text search dictionaries.
1502 If <replaceable class="parameter">pattern</replaceable> is specified,
1503 only dictionaries whose names match the pattern are shown.
1504 If the form <literal>\dFd+</literal> is used, additional information
1505 is shown about each selected dictionary, including the underlying
1506 text search template and the option values.
1512 <term><literal>\dFp[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1515 Lists text search parsers.
1516 If <replaceable class="parameter">pattern</replaceable> is specified,
1517 only parsers whose names match the pattern are shown.
1518 If the form <literal>\dFp+</literal> is used, a full description of
1519 each parser is shown, including the underlying functions and the
1520 list of recognized token types.
1526 <term><literal>\dFt[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1529 Lists text search templates.
1530 If <replaceable class="parameter">pattern</replaceable> is specified,
1531 only templates whose names match the pattern are shown.
1532 If the form <literal>\dFt+</literal> is used, additional information
1533 is shown about each template, including the underlying function names.
1540 <term><literal>\dg[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1543 Lists database roles.
1544 (Since the concepts of <quote>users</quote> and <quote>groups</quote> have been
1545 unified into <quote>roles</quote>, this command is now equivalent to
1546 <literal>\du</literal>.)
1547 By default, only user-created roles are shown; supply the
1548 <literal>S</literal> modifier to include system roles.
1549 If <replaceable class="parameter">pattern</replaceable> is specified,
1550 only those roles whose names match the pattern are listed.
1551 If the form <literal>\dg+</literal> is used, additional information
1552 is shown about each role; currently this adds the comment for each
1560 <term><literal>\dl</literal></term>
1563 This is an alias for <command>\lo_list</command>, which shows a
1564 list of large objects.
1570 <term><literal>\dL[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1573 Lists procedural languages. If <replaceable
1574 class="parameter">pattern</replaceable>
1575 is specified, only languages whose names match the pattern are listed.
1576 By default, only user-created languages
1577 are shown; supply the <literal>S</literal> modifier to include system
1578 objects. If <literal>+</literal> is appended to the command name, each
1579 language is listed with its call handler, validator, access privileges,
1580 and whether it is a system object.
1587 <term><literal>\dn[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1591 Lists schemas (namespaces). If <replaceable
1592 class="parameter">pattern</replaceable>
1593 is specified, only schemas whose names match the pattern are listed.
1594 By default, only user-created objects are shown; supply a
1595 pattern or the <literal>S</literal> modifier to include system objects.
1596 If <literal>+</literal> is appended to the command name, each object
1597 is listed with its associated permissions and description, if any.
1604 <term><literal>\do[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1607 Lists operators with their operand and result types.
1608 If <replaceable class="parameter">pattern</replaceable> is
1609 specified, only operators whose names match the pattern are listed.
1610 By default, only user-created objects are shown; supply a
1611 pattern or the <literal>S</literal> modifier to include system
1613 If <literal>+</literal> is appended to the command name,
1614 additional information about each operator is shown, currently just
1615 the name of the underlying function.
1622 <term><literal>\dO[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1626 If <replaceable class="parameter">pattern</replaceable> is
1627 specified, only collations whose names match the pattern are
1628 listed. By default, only user-created objects are shown;
1629 supply a pattern or the <literal>S</literal> modifier to
1630 include system objects. If <literal>+</literal> is appended
1631 to the command name, each collation is listed with its associated
1632 description, if any.
1633 Note that only collations usable with the current database's encoding
1634 are shown, so the results may vary in different databases of the
1642 <term><literal>\dp [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1645 Lists tables, views and sequences with their
1646 associated access privileges.
1647 If <replaceable class="parameter">pattern</replaceable> is
1648 specified, only tables, views and sequences whose names match the
1653 The <xref linkend="sql-grant"/> and
1654 <xref linkend="sql-revoke"/>
1655 commands are used to set access privileges. The meaning of the
1656 privilege display is explained in
1657 <xref linkend="ddl-priv"/>.
1663 <term><literal>\drds [ <link linkend="app-psql-patterns"><replaceable class="parameter">role-pattern</replaceable></link> [ <link linkend="app-psql-patterns"><replaceable class="parameter">database-pattern</replaceable></link> ] ]</literal></term>
1666 Lists defined configuration settings. These settings can be
1667 role-specific, database-specific, or both.
1668 <replaceable>role-pattern</replaceable> and
1669 <replaceable>database-pattern</replaceable> are used to select
1670 specific roles and databases to list, respectively. If omitted, or if
1671 <literal>*</literal> is specified, all settings are listed, including those
1672 not role-specific or database-specific, respectively.
1676 The <xref linkend="sql-alterrole"/> and
1677 <xref linkend="sql-alterdatabase"/>
1678 commands are used to define per-role and per-database configuration
1685 <term><literal>\dRp[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1688 Lists replication publications.
1689 If <replaceable class="parameter">pattern</replaceable> is
1690 specified, only those publications whose names match the pattern are
1692 If <literal>+</literal> is appended to the command name, the tables
1693 associated with each publication are shown as well.
1699 <term><literal>\dRs[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1702 Lists replication subscriptions.
1703 If <replaceable class="parameter">pattern</replaceable> is
1704 specified, only those subscriptions whose names match the pattern are
1706 If <literal>+</literal> is appended to the command name, additional
1707 properties of the subscriptions are shown.
1713 <term><literal>\dT[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1717 If <replaceable class="parameter">pattern</replaceable> is
1718 specified, only types whose names match the pattern are listed.
1719 If <literal>+</literal> is appended to the command name, each type is
1720 listed with its internal name and size, its allowed values
1721 if it is an <type>enum</type> type, and its associated permissions.
1722 By default, only user-created objects are shown; supply a
1723 pattern or the <literal>S</literal> modifier to include system
1730 <term><literal>\du[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1733 Lists database roles.
1734 (Since the concepts of <quote>users</quote> and <quote>groups</quote> have been
1735 unified into <quote>roles</quote>, this command is now equivalent to
1736 <literal>\dg</literal>.)
1737 By default, only user-created roles are shown; supply the
1738 <literal>S</literal> modifier to include system roles.
1739 If <replaceable class="parameter">pattern</replaceable> is specified,
1740 only those roles whose names match the pattern are listed.
1741 If the form <literal>\du+</literal> is used, additional information
1742 is shown about each role; currently this adds the comment for each
1749 <term><literal>\dx[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1752 Lists installed extensions.
1753 If <replaceable class="parameter">pattern</replaceable>
1754 is specified, only those extensions whose names match the pattern
1756 If the form <literal>\dx+</literal> is used, all the objects belonging
1757 to each matching extension are listed.
1763 <term><literal>\dy[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
1766 Lists event triggers.
1767 If <replaceable class="parameter">pattern</replaceable>
1768 is specified, only those event triggers whose names match the pattern
1770 If <literal>+</literal> is appended to the command name, each object
1771 is listed with its associated description.
1777 <term><literal>\e</literal> or <literal>\edit</literal> <literal> <optional> <replaceable class="parameter">filename</replaceable> </optional> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </literal></term>
1781 If <replaceable class="parameter">filename</replaceable> is
1782 specified, the file is edited; after the editor exits, the file's
1783 content is copied into the current query buffer. If no <replaceable
1784 class="parameter">filename</replaceable> is given, the current query
1785 buffer is copied to a temporary file which is then edited in the same
1786 fashion. Or, if the current query buffer is empty, the most recently
1787 executed query is copied to a temporary file and edited in the same
1792 The new contents of the query buffer are then re-parsed according to
1793 the normal rules of <application>psql</application>, treating the
1794 whole buffer as a single line. Any complete queries are immediately
1795 executed; that is, if the query buffer contains or ends with a
1796 semicolon, everything up to that point is executed. Whatever remains
1797 will wait in the query buffer; type semicolon or <literal>\g</literal> to
1798 send it, or <literal>\r</literal> to cancel it by clearing the query buffer.
1799 Treating the buffer as a single line primarily affects meta-commands:
1800 whatever is in the buffer after a meta-command will be taken as
1801 argument(s) to the meta-command, even if it spans multiple lines.
1802 (Thus you cannot make meta-command-using scripts this way.
1803 Use <command>\i</command> for that.)
1807 If a line number is specified, <application>psql</application> will
1808 position the cursor on the specified line of the file or query buffer.
1809 Note that if a single all-digits argument is given,
1810 <application>psql</application> assumes it is a line number,
1816 See under <xref linkend="app-psql-environment"
1817 endterm="app-psql-environment-title"/> for how to configure and
1818 customize your editor.
1825 <term><literal>\echo <replaceable class="parameter">text</replaceable> [ ... ]</literal></term>
1828 Prints the arguments to the standard output, separated by one
1829 space and followed by a newline. This can be useful to
1830 intersperse information in the output of scripts. For example:
1832 => <userinput>\echo `date`</userinput>
1833 Tue Oct 26 21:40:57 CEST 1999
1835 If the first argument is an unquoted <literal>-n</literal> the trailing
1836 newline is not written.
1841 If you use the <command>\o</command> command to redirect your
1842 query output you might wish to use <command>\qecho</command>
1843 instead of this command.
1850 <term><literal>\ef <optional> <replaceable class="parameter">function_description</replaceable> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </optional> </literal></term>
1854 This command fetches and edits the definition of the named function or procedure,
1855 in the form of a <command>CREATE OR REPLACE FUNCTION</command> or
1856 <command>CREATE OR REPLACE PROCEDURE</command> command.
1857 Editing is done in the same way as for <literal>\edit</literal>.
1858 After the editor exits, the updated command waits in the query buffer;
1859 type semicolon or <literal>\g</literal> to send it, or <literal>\r</literal>
1864 The target function can be specified by name alone, or by name
1865 and arguments, for example <literal>foo(integer, text)</literal>.
1866 The argument types must be given if there is more
1867 than one function of the same name.
1871 If no function is specified, a blank <command>CREATE FUNCTION</command>
1872 template is presented for editing.
1876 If a line number is specified, <application>psql</application> will
1877 position the cursor on the specified line of the function body.
1878 (Note that the function body typically does not begin on the first
1883 Unlike most other meta-commands, the entire remainder of the line is
1884 always taken to be the argument(s) of <command>\ef</command>, and neither
1885 variable interpolation nor backquote expansion are performed in the
1891 See under <xref linkend="app-psql-environment"
1892 endterm="app-psql-environment-title"/> for how to configure and
1893 customize your editor.
1901 <term><literal>\encoding [ <replaceable class="parameter">encoding</replaceable> ]</literal></term>
1905 Sets the client character set encoding. Without an argument, this command
1906 shows the current encoding.
1913 <term><literal>\errverbose</literal></term>
1917 Repeats the most recent server error message at maximum
1918 verbosity, as though <varname>VERBOSITY</varname> were set
1919 to <literal>verbose</literal> and <varname>SHOW_CONTEXT</varname> were
1920 set to <literal>always</literal>.
1927 <term><literal>\ev <optional> <replaceable class="parameter">view_name</replaceable> <optional> <replaceable class="parameter">line_number</replaceable> </optional> </optional> </literal></term>
1931 This command fetches and edits the definition of the named view,
1932 in the form of a <command>CREATE OR REPLACE VIEW</command> command.
1933 Editing is done in the same way as for <literal>\edit</literal>.
1934 After the editor exits, the updated command waits in the query buffer;
1935 type semicolon or <literal>\g</literal> to send it, or <literal>\r</literal>
1940 If no view is specified, a blank <command>CREATE VIEW</command>
1941 template is presented for editing.
1945 If a line number is specified, <application>psql</application> will
1946 position the cursor on the specified line of the view definition.
1950 Unlike most other meta-commands, the entire remainder of the line is
1951 always taken to be the argument(s) of <command>\ev</command>, and neither
1952 variable interpolation nor backquote expansion are performed in the
1960 <term><literal>\f [ <replaceable class="parameter">string</replaceable> ]</literal></term>
1964 Sets the field separator for unaligned query output. The default
1965 is the vertical bar (<literal>|</literal>). It is equivalent to
1966 <command>\pset fieldsep</command>.
1973 <term><literal>\g [ <replaceable class="parameter">filename</replaceable> ]</literal></term>
1974 <term><literal>\g [ |<replaceable class="parameter">command</replaceable> ]</literal></term>
1977 Sends the current query buffer to the server for execution.
1978 If an argument is given, the query's output is written to the named
1979 file or piped to the given shell command, instead of displaying it as
1980 usual. The file or command is written to only if the query
1981 successfully returns zero or more tuples, not if the query fails or
1982 is a non-data-returning SQL command.
1985 If the current query buffer is empty, the most recently sent query is
1986 re-executed instead. Except for that behavior, <literal>\g</literal>
1987 without an argument is essentially equivalent to a semicolon.
1988 A <literal>\g</literal> with argument is a <quote>one-shot</quote>
1989 alternative to the <command>\o</command> command.
1992 If the argument begins with <literal>|</literal>, then the entire remainder
1993 of the line is taken to be
1994 the <replaceable class="parameter">command</replaceable> to execute,
1995 and neither variable interpolation nor backquote expansion are
1996 performed in it. The rest of the line is simply passed literally to
2004 <term><literal>\gdesc</literal></term>
2008 Shows the description (that is, the column names and data types)
2009 of the result of the current query buffer. The query is not
2010 actually executed; however, if it contains some type of syntax
2011 error, that error will be reported in the normal way.
2015 If the current query buffer is empty, the most recently sent query
2016 is described instead.
2023 <term><literal>\gexec</literal></term>
2027 Sends the current query buffer to the server, then treats
2028 each column of each row of the query's output (if any) as a SQL
2029 statement to be executed. For example, to create an index on each
2030 column of <structname>my_table</structname>:
2032 => <userinput>SELECT format('create index on my_table(%I)', attname)</userinput>
2033 -> <userinput>FROM pg_attribute</userinput>
2034 -> <userinput>WHERE attrelid = 'my_table'::regclass AND attnum > 0</userinput>
2035 -> <userinput>ORDER BY attnum</userinput>
2036 -> <userinput>\gexec</userinput>
2045 The generated queries are executed in the order in which the rows
2046 are returned, and left-to-right within each row if there is more
2047 than one column. NULL fields are ignored. The generated queries
2048 are sent literally to the server for processing, so they cannot be
2049 <application>psql</application> meta-commands nor contain <application>psql</application>
2050 variable references. If any individual query fails, execution of
2051 the remaining queries continues
2052 unless <varname>ON_ERROR_STOP</varname> is set. Execution of each
2053 query is subject to <varname>ECHO</varname> processing.
2054 (Setting <varname>ECHO</varname> to <literal>all</literal>
2055 or <literal>queries</literal> is often advisable when
2056 using <command>\gexec</command>.) Query logging, single-step mode,
2057 timing, and other query execution features apply to each generated
2061 If the current query buffer is empty, the most recently sent query
2062 is re-executed instead.
2069 <term><literal>\gset [ <replaceable class="parameter">prefix</replaceable> ]</literal></term>
2073 Sends the current query buffer to the server and stores the
2074 query's output into <application>psql</application> variables (see <xref
2075 linkend="app-psql-variables" endterm="app-psql-variables-title"/>).
2076 The query to be executed must return exactly one row. Each column of
2077 the row is stored into a separate variable, named the same as the
2078 column. For example:
2080 => <userinput>SELECT 'hello' AS var1, 10 AS var2</userinput>
2081 -> <userinput>\gset</userinput>
2082 => <userinput>\echo :var1 :var2</userinput>
2087 If you specify a <replaceable class="parameter">prefix</replaceable>,
2088 that string is prepended to the query's column names to create the
2089 variable names to use:
2091 => <userinput>SELECT 'hello' AS var1, 10 AS var2</userinput>
2092 -> <userinput>\gset result_</userinput>
2093 => <userinput>\echo :result_var1 :result_var2</userinput>
2098 If a column result is NULL, the corresponding variable is unset
2099 rather than being set.
2102 If the query fails or does not return one row,
2103 no variables are changed.
2106 If the current query buffer is empty, the most recently sent query
2107 is re-executed instead.
2114 <term><literal>\gx [ <replaceable class="parameter">filename</replaceable> ]</literal></term>
2115 <term><literal>\gx [ |<replaceable class="parameter">command</replaceable> ]</literal></term>
2118 <literal>\gx</literal> is equivalent to <literal>\g</literal>, but
2119 forces expanded output mode for this query. See <literal>\x</literal>.
2126 <term><literal>\h</literal> or <literal>\help</literal> <literal>[ <replaceable class="parameter">command</replaceable> ]</literal></term>
2129 Gives syntax help on the specified <acronym>SQL</acronym>
2130 command. If <replaceable class="parameter">command</replaceable>
2131 is not specified, then <application>psql</application> will list
2132 all the commands for which syntax help is available. If
2133 <replaceable class="parameter">command</replaceable> is an
2134 asterisk (<literal>*</literal>), then syntax help on all
2135 <acronym>SQL</acronym> commands is shown.
2139 Unlike most other meta-commands, the entire remainder of the line is
2140 always taken to be the argument(s) of <command>\help</command>, and neither
2141 variable interpolation nor backquote expansion are performed in the
2147 To simplify typing, commands that consists of several words do
2148 not have to be quoted. Thus it is fine to type <userinput>\help
2149 alter table</userinput>.
2157 <term><literal>\H</literal> or <literal>\html</literal></term>
2160 Turns on <acronym>HTML</acronym> query output format. If the
2161 <acronym>HTML</acronym> format is already on, it is switched
2162 back to the default aligned text format. This command is for
2163 compatibility and convenience, but see <command>\pset</command>
2164 about setting other output options.
2171 <term><literal>\i</literal> or <literal>\include</literal> <replaceable class="parameter">filename</replaceable></term>
2174 Reads input from the file <replaceable
2175 class="parameter">filename</replaceable> and executes it as
2176 though it had been typed on the keyboard.
2179 If <replaceable>filename</replaceable> is <literal>-</literal>
2180 (hyphen), then standard input is read until an EOF indication
2181 or <command>\q</command> meta-command. This can be used to intersperse
2182 interactive input with input from files. Note that Readline behavior
2183 will be used only if it is active at the outermost level.
2187 If you want to see the lines on the screen as they are read you
2188 must set the variable <varname>ECHO</varname> to
2189 <literal>all</literal>.
2196 <varlistentry id="psql-metacommand-if">
2197 <term><literal>\if</literal> <replaceable class="parameter">expression</replaceable></term>
2198 <term><literal>\elif</literal> <replaceable class="parameter">expression</replaceable></term>
2199 <term><literal>\else</literal></term>
2200 <term><literal>\endif</literal></term>
2203 This group of commands implements nestable conditional blocks.
2204 A conditional block must begin with an <command>\if</command> and end
2205 with an <command>\endif</command>. In between there may be any number
2206 of <command>\elif</command> clauses, which may optionally be followed
2207 by a single <command>\else</command> clause. Ordinary queries and
2208 other types of backslash commands may (and usually do) appear between
2209 the commands forming a conditional block.
2212 The <command>\if</command> and <command>\elif</command> commands read
2213 their argument(s) and evaluate them as a boolean expression. If the
2214 expression yields <literal>true</literal> then processing continues
2215 normally; otherwise, lines are skipped until a
2216 matching <command>\elif</command>, <command>\else</command>,
2217 or <command>\endif</command> is reached. Once
2218 an <command>\if</command> or <command>\elif</command> test has
2219 succeeded, the arguments of later <command>\elif</command> commands in
2220 the same block are not evaluated but are treated as false. Lines
2221 following an <command>\else</command> are processed only if no earlier
2222 matching <command>\if</command> or <command>\elif</command> succeeded.
2225 The <replaceable class="parameter">expression</replaceable> argument
2226 of an <command>\if</command> or <command>\elif</command> command
2227 is subject to variable interpolation and backquote expansion, just
2228 like any other backslash command argument. After that it is evaluated
2229 like the value of an on/off option variable. So a valid value
2230 is any unambiguous case-insensitive match for one of:
2231 <literal>true</literal>, <literal>false</literal>, <literal>1</literal>,
2232 <literal>0</literal>, <literal>on</literal>, <literal>off</literal>,
2233 <literal>yes</literal>, <literal>no</literal>. For example,
2234 <literal>t</literal>, <literal>T</literal>, and <literal>tR</literal>
2235 will all be considered to be <literal>true</literal>.
2238 Expressions that do not properly evaluate to true or false will
2239 generate a warning and be treated as false.
2242 Lines being skipped are parsed normally to identify queries and
2243 backslash commands, but queries are not sent to the server, and
2244 backslash commands other than conditionals
2245 (<command>\if</command>, <command>\elif</command>,
2246 <command>\else</command>, <command>\endif</command>) are
2247 ignored. Conditional commands are checked only for valid nesting.
2248 Variable references in skipped lines are not expanded, and backquote
2249 expansion is not performed either.
2252 All the backslash commands of a given conditional block must appear in
2253 the same source file. If EOF is reached on the main input file or an
2254 <command>\include</command>-ed file before all local
2255 <command>\if</command>-blocks have been closed,
2256 then <application>psql</application> will raise an error.
2262 -- check for the existence of two separate records in the database and store
2263 -- the results in separate psql variables
2265 EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer,
2266 EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee
2269 SELECT * FROM customer WHERE customer_id = 123;
2271 \echo 'is not a customer but is an employee'
2272 SELECT * FROM employee WHERE employee_id = 456;
2275 \echo 'not a customer or employee'
2277 \echo 'this will never print'
2286 <term><literal>\ir</literal> or <literal>\include_relative</literal> <replaceable class="parameter">filename</replaceable></term>
2289 The <literal>\ir</literal> command is similar to <literal>\i</literal>, but resolves
2290 relative file names differently. When executing in interactive mode,
2291 the two commands behave identically. However, when invoked from a
2292 script, <literal>\ir</literal> interprets file names relative to the
2293 directory in which the script is located, rather than the current
2301 <term><literal>\l[+]</literal> or <literal>\list[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
2304 List the databases in the server and show their names, owners,
2305 character set encodings, and access privileges.
2306 If <replaceable class="parameter">pattern</replaceable> is specified,
2307 only databases whose names match the pattern are listed.
2308 If <literal>+</literal> is appended to the command name, database
2309 sizes, default tablespaces, and descriptions are also displayed.
2310 (Size information is only available for databases that the current
2311 user can connect to.)
2318 <term><literal>\lo_export <replaceable class="parameter">loid</replaceable> <replaceable class="parameter">filename</replaceable></literal></term>
2322 Reads the large object with <acronym>OID</acronym> <replaceable
2323 class="parameter">loid</replaceable> from the database and
2324 writes it to <replaceable
2325 class="parameter">filename</replaceable>. Note that this is
2326 subtly different from the server function
2327 <function>lo_export</function>, which acts with the permissions
2328 of the user that the database server runs as and on the server's
2333 Use <command>\lo_list</command> to find out the large object's
2334 <acronym>OID</acronym>.
2342 <term><literal>\lo_import <replaceable class="parameter">filename</replaceable> [ <replaceable class="parameter">comment</replaceable> ]</literal></term>
2346 Stores the file into a <productname>PostgreSQL</productname>
2347 large object. Optionally, it associates the given
2348 comment with the object. Example:
2350 foo=> <userinput>\lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'</userinput>
2353 The response indicates that the large object received object
2354 ID 152801, which can be used to access the newly-created large
2355 object in the future. For the sake of readability, it is
2356 recommended to always associate a human-readable comment with
2357 every object. Both OIDs and comments can be viewed with the
2358 <command>\lo_list</command> command.
2362 Note that this command is subtly different from the server-side
2363 <function>lo_import</function> because it acts as the local user
2364 on the local file system, rather than the server's user and file
2371 <term><literal>\lo_list</literal></term>
2374 Shows a list of all <productname>PostgreSQL</productname>
2375 large objects currently stored in the database,
2376 along with any comments provided for them.
2382 <term><literal>\lo_unlink <replaceable class="parameter">loid</replaceable></literal></term>
2386 Deletes the large object with <acronym>OID</acronym>
2387 <replaceable class="parameter">loid</replaceable> from the
2393 Use <command>\lo_list</command> to find out the large object's
2394 <acronym>OID</acronym>.
2402 <term><literal>\o</literal> or <literal>\out [ <replaceable class="parameter">filename</replaceable> ]</literal></term>
2403 <term><literal>\o</literal> or <literal>\out [ |<replaceable class="parameter">command</replaceable> ]</literal></term>
2406 Arranges to save future query results to the file <replaceable
2407 class="parameter">filename</replaceable> or pipe future results
2408 to the shell command <replaceable
2409 class="parameter">command</replaceable>. If no argument is
2410 specified, the query output is reset to the standard output.
2414 If the argument begins with <literal>|</literal>, then the entire remainder
2415 of the line is taken to be
2416 the <replaceable class="parameter">command</replaceable> to execute,
2417 and neither variable interpolation nor backquote expansion are
2418 performed in it. The rest of the line is simply passed literally to
2423 <quote>Query results</quote> includes all tables, command
2424 responses, and notices obtained from the database server, as
2425 well as output of various backslash commands that query the
2426 database (such as <command>\d</command>); but not error
2432 To intersperse text output in between query results, use
2433 <command>\qecho</command>.
2441 <term><literal>\p</literal> or <literal>\print</literal></term>
2444 Print the current query buffer to the standard output.
2445 If the current query buffer is empty, the most recently executed query
2452 <term><literal>\password [ <replaceable class="parameter">username</replaceable> ]</literal></term>
2455 Changes the password of the specified user (by default, the current
2456 user). This command prompts for the new password, encrypts it, and
2457 sends it to the server as an <command>ALTER ROLE</command> command. This
2458 makes sure that the new password does not appear in cleartext in the
2459 command history, the server log, or elsewhere.
2465 <term><literal>\prompt [ <replaceable class="parameter">text</replaceable> ] <replaceable class="parameter">name</replaceable></literal></term>
2468 Prompts the user to supply text, which is assigned to the variable
2469 <replaceable class="parameter">name</replaceable>.
2470 An optional prompt string, <replaceable
2471 class="parameter">text</replaceable>, can be specified. (For multiword
2472 prompts, surround the text with single quotes.)
2476 By default, <literal>\prompt</literal> uses the terminal for input and
2477 output. However, if the <option>-f</option> command line switch was
2478 used, <literal>\prompt</literal> uses standard input and standard output.
2484 <term><literal>\pset [ <replaceable class="parameter">option</replaceable> [ <replaceable class="parameter">value</replaceable> ] ]</literal></term>
2488 This command sets options affecting the output of query result tables.
2489 <replaceable class="parameter">option</replaceable>
2490 indicates which option is to be set. The semantics of
2491 <replaceable class="parameter">value</replaceable> vary depending
2492 on the selected option. For some options, omitting <replaceable
2493 class="parameter">value</replaceable> causes the option to be toggled
2494 or unset, as described under the particular option. If no such
2495 behavior is mentioned, then omitting
2496 <replaceable class="parameter">value</replaceable> just results in
2497 the current setting being displayed.
2501 <command>\pset</command> without any arguments displays the current status
2502 of all printing options.
2506 Adjustable printing options are:
2509 <term><literal>border</literal></term>
2512 The <replaceable class="parameter">value</replaceable> must be a
2513 number. In general, the higher
2514 the number the more borders and lines the tables will have,
2515 but details depend on the particular format.
2516 In <acronym>HTML</acronym> format, this will translate directly
2517 into the <literal>border=...</literal> attribute.
2518 In most other formats only values 0 (no border), 1 (internal
2519 dividing lines), and 2 (table frame) make sense, and values above 2
2520 will be treated the same as <literal>border = 2</literal>.
2521 The <literal>latex</literal> and <literal>latex-longtable</literal>
2522 formats additionally allow a value of 3 to add dividing lines
2529 <term><literal>columns</literal></term>
2532 Sets the target width for the <literal>wrapped</literal> format, and also
2533 the width limit for determining whether output is wide enough to
2534 require the pager or switch to the vertical display in expanded auto
2536 Zero (the default) causes the target width to be controlled by the
2537 environment variable <envar>COLUMNS</envar>, or the detected screen width
2538 if <envar>COLUMNS</envar> is not set.
2539 In addition, if <literal>columns</literal> is zero then the
2540 <literal>wrapped</literal> format only affects screen output.
2541 If <literal>columns</literal> is nonzero then file and pipe output is
2542 wrapped to that width as well.
2548 <term><literal>csv_fieldsep</literal></term>
2551 Specifies the field separator to be used in
2552 <acronym>CSV</acronym> output format. If the separator character
2553 appears in a field's value, that field is output within double
2554 quotes, following standard <acronym>CSV</acronym> rules.
2555 The default is a comma.
2561 <term><literal>expanded</literal> (or <literal>x</literal>)</term>
2564 If <replaceable class="parameter">value</replaceable> is specified it
2565 must be either <literal>on</literal> or <literal>off</literal>, which
2566 will enable or disable expanded mode, or <literal>auto</literal>.
2567 If <replaceable class="parameter">value</replaceable> is omitted the
2568 command toggles between the on and off settings. When expanded mode
2569 is enabled, query results are displayed in two columns, with the
2570 column name on the left and the data on the right. This mode is
2571 useful if the data wouldn't fit on the screen in the
2572 normal <quote>horizontal</quote> mode. In the auto setting, the
2573 expanded mode is used whenever the query output has more than one
2574 column and is wider than the screen; otherwise, the regular mode is
2575 used. The auto setting is only
2576 effective in the aligned and wrapped formats. In other formats, it
2577 always behaves as if the expanded mode is off.
2583 <term><literal>fieldsep</literal></term>
2586 Specifies the field separator to be used in unaligned output
2587 format. That way one can create, for example, tab-separated
2588 output, which other programs might prefer. To
2589 set a tab as field separator, type <literal>\pset fieldsep
2590 '\t'</literal>. The default field separator is
2591 <literal>'|'</literal> (a vertical bar).
2597 <term><literal>fieldsep_zero</literal></term>
2600 Sets the field separator to use in unaligned output format to a zero
2607 <term><literal>footer</literal></term>
2610 If <replaceable class="parameter">value</replaceable> is specified
2611 it must be either <literal>on</literal> or <literal>off</literal>
2612 which will enable or disable display of the table footer
2613 (the <literal>(<replaceable>n</replaceable> rows)</literal> count).
2614 If <replaceable class="parameter">value</replaceable> is omitted the
2615 command toggles footer display on or off.
2621 <term><literal>format</literal></term>
2624 Sets the output format to one of <literal>aligned</literal>,
2625 <literal>asciidoc</literal>,
2626 <literal>csv</literal>,
2627 <literal>html</literal>,
2628 <literal>latex</literal>,
2629 <literal>latex-longtable</literal>, <literal>troff-ms</literal>,
2630 <literal>unaligned</literal>, or <literal>wrapped</literal>.
2631 Unique abbreviations are allowed.
2634 <para><literal>aligned</literal> format is the standard,
2635 human-readable, nicely formatted text output; this is the default.
2638 <para><literal>unaligned</literal> format writes all columns of a row on one
2639 line, separated by the currently active field separator. This
2640 is useful for creating output that might be intended to be read
2641 in by other programs, for example, tab-separated or comma-separated
2642 format. However, the field separator character is not treated
2643 specially if it appears in a column's value;
2644 so <acronym>CSV</acronym> format may be better suited for such
2648 <para><literal>csv</literal> format
2650 <primary>CSV (Comma-Separated Values) format</primary>
2651 <secondary>in psql</secondary>
2653 writes column values separated by commas, applying the quoting
2655 <ulink url="https://tools.ietf.org/html/rfc4180">RFC 4180</ulink>.
2656 This output is compatible with the CSV format of the server's
2657 <command>COPY</command> command.
2658 A header line with column names is generated unless
2659 the <literal>tuples_only</literal> parameter is
2660 <literal>on</literal>. Titles and footers are not printed.
2661 Each row is terminated by the system-dependent end-of-line character,
2662 which is typically a single newline (<literal>\n</literal>) for
2663 Unix-like systems or a carriage return and newline sequence
2664 (<literal>\r\n</literal>) for Microsoft Windows.
2665 Field separator characters other than comma can be selected with
2666 <command>\pset csv_fieldsep</command>.
2669 <para><literal>wrapped</literal> format is like <literal>aligned</literal> but wraps
2670 wide data values across lines to make the output fit in the target
2671 column width. The target width is determined as described under
2672 the <literal>columns</literal> option. Note that <application>psql</application> will
2673 not attempt to wrap column header titles; therefore,
2674 <literal>wrapped</literal> format behaves the same as <literal>aligned</literal>
2675 if the total width needed for column headers exceeds the target.
2679 The <literal>asciidoc</literal>, <literal>html</literal>,
2680 <literal>latex</literal>, <literal>latex-longtable</literal>, and
2681 <literal>troff-ms</literal> formats put out tables that are intended
2682 to be included in documents using the respective mark-up
2683 language. They are not complete documents! This might not be
2684 necessary in <acronym>HTML</acronym>, but in
2685 <application>LaTeX</application> you must have a complete
2687 The <literal>latex</literal> format
2688 uses <application>LaTeX</application>'s <literal>tabular</literal>
2690 The <literal>latex-longtable</literal> format
2691 requires the <application>LaTeX</application>
2692 <literal>longtable</literal> and <literal>booktabs</literal> packages.
2698 <term><literal>linestyle</literal></term>
2701 Sets the border line drawing style to one
2702 of <literal>ascii</literal>, <literal>old-ascii</literal>,
2703 or <literal>unicode</literal>.
2704 Unique abbreviations are allowed. (That would mean one
2706 The default setting is <literal>ascii</literal>.
2707 This option only affects the <literal>aligned</literal> and
2708 <literal>wrapped</literal> output formats.
2711 <para><literal>ascii</literal> style uses plain <acronym>ASCII</acronym>
2712 characters. Newlines in data are shown using
2713 a <literal>+</literal> symbol in the right-hand margin.
2714 When the <literal>wrapped</literal> format wraps data from
2715 one line to the next without a newline character, a dot
2716 (<literal>.</literal>) is shown in the right-hand margin of the first line,
2717 and again in the left-hand margin of the following line.
2720 <para><literal>old-ascii</literal> style uses plain <acronym>ASCII</acronym>
2721 characters, using the formatting style used
2722 in <productname>PostgreSQL</productname> 8.4 and earlier.
2723 Newlines in data are shown using a <literal>:</literal>
2724 symbol in place of the left-hand column separator.
2725 When the data is wrapped from one line
2726 to the next without a newline character, a <literal>;</literal>
2727 symbol is used in place of the left-hand column separator.
2730 <para><literal>unicode</literal> style uses Unicode box-drawing characters.
2731 Newlines in data are shown using a carriage return symbol
2732 in the right-hand margin. When the data is wrapped from one line
2733 to the next without a newline character, an ellipsis symbol
2734 is shown in the right-hand margin of the first line, and
2735 again in the left-hand margin of the following line.
2739 When the <literal>border</literal> setting is greater than zero,
2740 the <literal>linestyle</literal> option also determines the
2741 characters with which the border lines are drawn.
2742 Plain <acronym>ASCII</acronym> characters work everywhere, but
2743 Unicode characters look nicer on displays that recognize them.
2749 <term><literal>null</literal></term>
2752 Sets the string to be printed in place of a null value.
2753 The default is to print nothing, which can easily be mistaken for
2754 an empty string. For example, one might prefer <literal>\pset null
2761 <term><literal>numericlocale</literal></term>
2764 If <replaceable class="parameter">value</replaceable> is specified
2765 it must be either <literal>on</literal> or <literal>off</literal>
2766 which will enable or disable display of a locale-specific character
2767 to separate groups of digits to the left of the decimal marker.
2768 If <replaceable class="parameter">value</replaceable> is omitted the
2769 command toggles between regular and locale-specific numeric output.
2775 <term><literal>pager</literal></term>
2778 Controls use of a pager program for query and <application>psql</application>
2779 help output. If the environment variable <envar>PSQL_PAGER</envar>
2780 or <envar>PAGER</envar> is set, the output is piped to the
2781 specified program. Otherwise a platform-dependent default program
2782 (such as <filename>more</filename>) is used.
2786 When the <literal>pager</literal> option is <literal>off</literal>, the pager
2787 program is not used. When the <literal>pager</literal> option is
2788 <literal>on</literal>, the pager is used when appropriate, i.e., when the
2789 output is to a terminal and will not fit on the screen.
2790 The <literal>pager</literal> option can also be set to <literal>always</literal>,
2791 which causes the pager to be used for all terminal output regardless
2792 of whether it fits on the screen. <literal>\pset pager</literal>
2793 without a <replaceable class="parameter">value</replaceable>
2794 toggles pager use on and off.
2800 <term><literal>pager_min_lines</literal></term>
2803 If <literal>pager_min_lines</literal> is set to a number greater than the
2804 page height, the pager program will not be called unless there are
2805 at least this many lines of output to show. The default setting
2812 <term><literal>recordsep</literal></term>
2815 Specifies the record (line) separator to use in unaligned
2816 output format. The default is a newline character.
2822 <term><literal>recordsep_zero</literal></term>
2825 Sets the record separator to use in unaligned output format to a zero
2832 <term><literal>tableattr</literal> (or <literal>T</literal>)</term>
2835 In <acronym>HTML</acronym> format, this specifies attributes
2836 to be placed inside the <sgmltag>table</sgmltag> tag. This
2837 could for example be <literal>cellpadding</literal> or
2838 <literal>bgcolor</literal>. Note that you probably don't want
2839 to specify <literal>border</literal> here, as that is already
2840 taken care of by <literal>\pset border</literal>.
2842 <replaceable class="parameter">value</replaceable> is given,
2843 the table attributes are unset.
2846 In <literal>latex-longtable</literal> format, this controls
2847 the proportional width of each column containing a left-aligned
2848 data type. It is specified as a whitespace-separated list of values,
2849 e.g. <literal>'0.2 0.2 0.6'</literal>. Unspecified output columns
2850 use the last specified value.
2856 <term><literal>title</literal> (or <literal>C</literal>)</term>
2859 Sets the table title for any subsequently printed tables. This
2860 can be used to give your output descriptive tags. If no
2861 <replaceable class="parameter">value</replaceable> is given,
2868 <term><literal>tuples_only</literal> (or <literal>t</literal>)</term>
2871 If <replaceable class="parameter">value</replaceable> is specified
2872 it must be either <literal>on</literal> or <literal>off</literal>
2873 which will enable or disable tuples-only mode.
2874 If <replaceable class="parameter">value</replaceable> is omitted the
2875 command toggles between regular and tuples-only output.
2876 Regular output includes extra information such
2877 as column headers, titles, and various footers. In tuples-only
2878 mode, only actual table data is shown.
2884 <term><literal>unicode_border_linestyle</literal></term>
2887 Sets the border drawing style for the <literal>unicode</literal>
2888 line style to one of <literal>single</literal>
2889 or <literal>double</literal>.
2895 <term><literal>unicode_column_linestyle</literal></term>
2898 Sets the column drawing style for the <literal>unicode</literal>
2899 line style to one of <literal>single</literal>
2900 or <literal>double</literal>.
2906 <term><literal>unicode_header_linestyle</literal></term>
2909 Sets the header drawing style for the <literal>unicode</literal>
2910 line style to one of <literal>single</literal>
2911 or <literal>double</literal>.
2919 Illustrations of how these different formats look can be seen in
2920 the <xref linkend="app-psql-examples"
2921 endterm="app-psql-examples-title"/> section.
2926 There are various shortcut commands for <command>\pset</command>. See
2927 <command>\a</command>, <command>\C</command>, <command>\f</command>,
2928 <command>\H</command>, <command>\t</command>, <command>\T</command>,
2929 and <command>\x</command>.
2938 <term><literal>\q</literal> or <literal>\quit</literal></term>
2941 Quits the <application>psql</application> program.
2942 In a script file, only execution of that script is terminated.
2949 <term><literal>\qecho <replaceable class="parameter">text</replaceable> [ ... ] </literal></term>
2952 This command is identical to <command>\echo</command> except
2953 that the output will be written to the query output channel, as
2954 set by <command>\o</command>.
2961 <term><literal>\r</literal> or <literal>\reset</literal></term>
2964 Resets (clears) the query buffer.
2971 <term><literal>\s [ <replaceable class="parameter">filename</replaceable> ]</literal></term>
2974 Print <application>psql</application>'s command line history
2975 to <replaceable class="parameter">filename</replaceable>.
2976 If <replaceable class="parameter">filename</replaceable> is omitted,
2977 the history is written to the standard output (using the pager if
2978 appropriate). This command is not available
2979 if <application>psql</application> was built
2980 without <application>Readline</application> support.
2987 <term><literal>\set [ <replaceable class="parameter">name</replaceable> [ <replaceable class="parameter">value</replaceable> [ ... ] ] ]</literal></term>
2991 Sets the <application>psql</application> variable <replaceable
2992 class="parameter">name</replaceable> to <replaceable
2993 class="parameter">value</replaceable>, or if more than one value
2994 is given, to the concatenation of all of them. If only one
2995 argument is given, the variable is set to an empty-string value. To
2996 unset a variable, use the <command>\unset</command> command.
2999 <para><command>\set</command> without any arguments displays the names and values
3000 of all currently-set <application>psql</application> variables.
3004 Valid variable names can contain letters, digits, and
3005 underscores. See the section <xref
3006 linkend="app-psql-variables"
3007 endterm="app-psql-variables-title"/> below for details.
3008 Variable names are case-sensitive.
3012 Certain variables are special, in that they
3013 control <application>psql</application>'s behavior or are
3014 automatically set to reflect connection state. These variables are
3015 documented in <xref linkend="app-psql-variables"
3016 endterm="app-psql-variables-title"/>, below.
3021 This command is unrelated to the <acronym>SQL</acronym>
3022 command <xref linkend="sql-set"/>.
3030 <term><literal>\setenv <replaceable class="parameter">name</replaceable> [ <replaceable class="parameter">value</replaceable> ]</literal></term>
3034 Sets the environment variable <replaceable
3035 class="parameter">name</replaceable> to <replaceable
3036 class="parameter">value</replaceable>, or if the
3037 <replaceable class="parameter">value</replaceable> is
3038 not supplied, unsets the environment variable. Example:
3040 testdb=> <userinput>\setenv PAGER less</userinput>
3041 testdb=> <userinput>\setenv LESS -imx4F</userinput>
3042 </programlisting></para>
3047 <term><literal>\sf[+] <replaceable class="parameter">function_description</replaceable> </literal></term>
3051 This command fetches and shows the definition of the named function or procedure,
3052 in the form of a <command>CREATE OR REPLACE FUNCTION</command> or
3053 <command>CREATE OR REPLACE PROCEDURE</command> command.
3054 The definition is printed to the current query output channel,
3055 as set by <command>\o</command>.
3059 The target function can be specified by name alone, or by name
3060 and arguments, for example <literal>foo(integer, text)</literal>.
3061 The argument types must be given if there is more
3062 than one function of the same name.
3066 If <literal>+</literal> is appended to the command name, then the
3067 output lines are numbered, with the first line of the function body
3072 Unlike most other meta-commands, the entire remainder of the line is
3073 always taken to be the argument(s) of <command>\sf</command>, and neither
3074 variable interpolation nor backquote expansion are performed in the
3082 <term><literal>\sv[+] <replaceable class="parameter">view_name</replaceable> </literal></term>
3086 This command fetches and shows the definition of the named view,
3087 in the form of a <command>CREATE OR REPLACE VIEW</command> command.
3088 The definition is printed to the current query output channel,
3089 as set by <command>\o</command>.
3093 If <literal>+</literal> is appended to the command name, then the
3094 output lines are numbered from 1.
3098 Unlike most other meta-commands, the entire remainder of the line is
3099 always taken to be the argument(s) of <command>\sv</command>, and neither
3100 variable interpolation nor backquote expansion are performed in the
3108 <term><literal>\t</literal></term>
3111 Toggles the display of output column name headings and row count
3112 footer. This command is equivalent to <literal>\pset
3113 tuples_only</literal> and is provided for convenience.
3120 <term><literal>\T <replaceable class="parameter">table_options</replaceable></literal></term>
3123 Specifies attributes to be placed within the
3124 <sgmltag>table</sgmltag> tag in <acronym>HTML</acronym>
3125 output format. This command is equivalent to <literal>\pset
3126 tableattr <replaceable
3127 class="parameter">table_options</replaceable></literal>.
3134 <term><literal>\timing [ <replaceable class="parameter">on</replaceable> | <replaceable class="parameter">off</replaceable> ]</literal></term>
3137 With a parameter, turns displaying of how long each SQL statement
3138 takes on or off. Without a parameter, toggles the display between
3139 on and off. The display is in milliseconds; intervals longer than
3140 1 second are also shown in minutes:seconds format, with hours and
3141 days fields added if needed.
3148 <term><literal>\unset <replaceable class="parameter">name</replaceable></literal></term>
3152 Unsets (deletes) the <application>psql</application> variable <replaceable
3153 class="parameter">name</replaceable>.
3157 Most variables that control <application>psql</application>'s behavior
3158 cannot be unset; instead, an <literal>\unset</literal> command is interpreted
3159 as setting them to their default values.
3160 See <xref linkend="app-psql-variables"
3161 endterm="app-psql-variables-title"/>, below.
3168 <term><literal>\w</literal> or <literal>\write</literal> <replaceable class="parameter">filename</replaceable></term>
3169 <term><literal>\w</literal> or <literal>\write</literal> <literal>|</literal><replaceable class="parameter">command</replaceable></term>
3172 Writes the current query buffer to the file <replaceable
3173 class="parameter">filename</replaceable> or pipes it to the shell
3174 command <replaceable class="parameter">command</replaceable>.
3175 If the current query buffer is empty, the most recently executed query
3180 If the argument begins with <literal>|</literal>, then the entire remainder
3181 of the line is taken to be
3182 the <replaceable class="parameter">command</replaceable> to execute,
3183 and neither variable interpolation nor backquote expansion are
3184 performed in it. The rest of the line is simply passed literally to
3192 <term><literal>\watch [ <replaceable class="parameter">seconds</replaceable> ]</literal></term>
3195 Repeatedly execute the current query buffer (as <literal>\g</literal> does)
3196 until interrupted or the query fails. Wait the specified number of
3197 seconds (default 2) between executions. Each query result is
3198 displayed with a header that includes the <literal>\pset title</literal>
3199 string (if any), the time as of query start, and the delay interval.
3202 If the current query buffer is empty, the most recently sent query
3203 is re-executed instead.
3210 <term><literal>\x [ <replaceable class="parameter">on</replaceable> | <replaceable class="parameter">off</replaceable> | <replaceable class="parameter">auto</replaceable> ]</literal></term>
3213 Sets or toggles expanded table formatting mode. As such it is equivalent to
3214 <literal>\pset expanded</literal>.
3221 <term><literal>\z [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
3224 Lists tables, views and sequences with their
3225 associated access privileges.
3226 If a <replaceable class="parameter">pattern</replaceable> is
3227 specified, only tables, views and sequences whose names match the
3232 This is an alias for <command>\dp</command> (<quote>display
3233 privileges</quote>).
3240 <term><literal>\! [ <replaceable class="parameter">command</replaceable> ]</literal></term>
3243 With no argument, escapes to a sub-shell; <application>psql</application>
3244 resumes when the sub-shell exits. With an argument, executes the
3245 shell command <replaceable class="parameter">command</replaceable>.
3249 Unlike most other meta-commands, the entire remainder of the line is
3250 always taken to be the argument(s) of <command>\!</command>, and neither
3251 variable interpolation nor backquote expansion are performed in the
3252 arguments. The rest of the line is simply passed literally to the
3260 <term><literal>\? [ <replaceable class="parameter">topic</replaceable> ]</literal></term>
3263 Shows help information. The optional
3264 <replaceable class="parameter">topic</replaceable> parameter
3265 (defaulting to <literal>commands</literal>) selects which part of <application>psql</application> is
3266 explained: <literal>commands</literal> describes <application>psql</application>'s
3267 backslash commands; <literal>options</literal> describes the command-line
3268 options that can be passed to <application>psql</application>;
3269 and <literal>variables</literal> shows help about <application>psql</application> configuration
3277 <term><literal>\;</literal></term>
3280 Backslash-semicolon is not a meta-command in the same way as the
3281 preceding commands; rather, it simply causes a semicolon to be
3282 added to the query buffer without any further processing.
3286 Normally, <application>psql</application> will dispatch a SQL command to the
3287 server as soon as it reaches the command-ending semicolon, even if
3288 more input remains on the current line. Thus for example entering
3290 select 1; select 2; select 3;
3292 will result in the three SQL commands being individually sent to
3293 the server, with each one's results being displayed before
3294 continuing to the next command. However, a semicolon entered
3295 as <literal>\;</literal> will not trigger command processing, so that the
3296 command before it and the one after are effectively combined and
3297 sent to the server in one request. So for example
3299 select 1\; select 2\; select 3;
3301 results in sending the three SQL commands to the server in a single
3302 request, when the non-backslashed semicolon is reached.
3303 The server executes such a request as a single transaction,
3304 unless there are explicit <command>BEGIN</command>/<command>COMMIT</command>
3305 commands included in the string to divide it into multiple
3306 transactions. (See <xref linkend="protocol-flow-multi-statement"/>
3307 for more details about how the server handles multi-query strings.)
3308 <application>psql</application> prints only the last query result
3309 it receives for each request; in this example, although all
3310 three <command>SELECT</command>s are indeed executed, <application>psql</application>
3311 only prints the <literal>3</literal>.
3319 <refsect3 id="app-psql-patterns">
3320 <title id="app-psql-patterns-title">Patterns</title>
3323 <primary>patterns</primary>
3324 <secondary>in psql and pg_dump</secondary>
3328 The various <literal>\d</literal> commands accept a <replaceable
3329 class="parameter">pattern</replaceable> parameter to specify the
3330 object name(s) to be displayed. In the simplest case, a pattern
3331 is just the exact name of the object. The characters within a
3332 pattern are normally folded to lower case, just as in SQL names;
3333 for example, <literal>\dt FOO</literal> will display the table named
3334 <literal>foo</literal>. As in SQL names, placing double quotes around
3335 a pattern stops folding to lower case. Should you need to include
3336 an actual double quote character in a pattern, write it as a pair
3337 of double quotes within a double-quote sequence; again this is in
3338 accord with the rules for SQL quoted identifiers. For example,
3339 <literal>\dt "FOO""BAR"</literal> will display the table named
3340 <literal>FOO"BAR</literal> (not <literal>foo"bar</literal>). Unlike the normal
3341 rules for SQL names, you can put double quotes around just part
3342 of a pattern, for instance <literal>\dt FOO"FOO"BAR</literal> will display
3343 the table named <literal>fooFOObar</literal>.
3347 Whenever the <replaceable class="parameter">pattern</replaceable> parameter
3348 is omitted completely, the <literal>\d</literal> commands display all objects
3349 that are visible in the current schema search path — this is
3350 equivalent to using <literal>*</literal> as the pattern.
3351 (An object is said to be <firstterm>visible</firstterm> if its
3352 containing schema is in the search path and no object of the same
3353 kind and name appears earlier in the search path. This is equivalent to the
3354 statement that the object can be referenced by name without explicit
3355 schema qualification.)
3356 To see all objects in the database regardless of visibility,
3357 use <literal>*.*</literal> as the pattern.
3361 Within a pattern, <literal>*</literal> matches any sequence of characters
3362 (including no characters) and <literal>?</literal> matches any single character.
3363 (This notation is comparable to Unix shell file name patterns.)
3364 For example, <literal>\dt int*</literal> displays tables whose names
3365 begin with <literal>int</literal>. But within double quotes, <literal>*</literal>
3366 and <literal>?</literal> lose these special meanings and are just matched
3371 A pattern that contains a dot (<literal>.</literal>) is interpreted as a schema
3372 name pattern followed by an object name pattern. For example,
3373 <literal>\dt foo*.*bar*</literal> displays all tables whose table name
3374 includes <literal>bar</literal> that are in schemas whose schema name
3375 starts with <literal>foo</literal>. When no dot appears, then the pattern
3376 matches only objects that are visible in the current schema search path.
3377 Again, a dot within double quotes loses its special meaning and is matched
3382 Advanced users can use regular-expression notations such as character
3383 classes, for example <literal>[0-9]</literal> to match any digit. All regular
3384 expression special characters work as specified in
3385 <xref linkend="functions-posix-regexp"/>, except for <literal>.</literal> which
3386 is taken as a separator as mentioned above, <literal>*</literal> which is
3387 translated to the regular-expression notation <literal>.*</literal>,
3388 <literal>?</literal> which is translated to <literal>.</literal>, and
3389 <literal>$</literal> which is matched literally. You can emulate
3390 these pattern characters at need by writing
3391 <literal>?</literal> for <literal>.</literal>,
3392 <literal>(<replaceable class="parameter">R</replaceable>+|)</literal> for
3393 <literal><replaceable class="parameter">R</replaceable>*</literal>, or
3394 <literal>(<replaceable class="parameter">R</replaceable>|)</literal> for
3395 <literal><replaceable class="parameter">R</replaceable>?</literal>.
3396 <literal>$</literal> is not needed as a regular-expression character since
3397 the pattern must match the whole name, unlike the usual
3398 interpretation of regular expressions (in other words, <literal>$</literal>
3399 is automatically appended to your pattern). Write <literal>*</literal> at the
3400 beginning and/or end if you don't wish the pattern to be anchored.
3401 Note that within double quotes, all regular expression special characters
3402 lose their special meanings and are matched literally. Also, the regular
3403 expression special characters are matched literally in operator name
3404 patterns (i.e., the argument of <literal>\do</literal>).
3410 <title>Advanced Features</title>
3412 <refsect3 id="app-psql-variables">
3413 <title id="app-psql-variables-title">Variables</title>
3416 <application>psql</application> provides variable substitution
3417 features similar to common Unix command shells.
3418 Variables are simply name/value pairs, where the value
3419 can be any string of any length. The name must consist of letters
3420 (including non-Latin letters), digits, and underscores.
3424 To set a variable, use the <application>psql</application> meta-command
3425 <command>\set</command>. For example,
3427 testdb=> <userinput>\set foo bar</userinput>
3429 sets the variable <literal>foo</literal> to the value
3430 <literal>bar</literal>. To retrieve the content of the variable, precede
3431 the name with a colon, for example:
3433 testdb=> <userinput>\echo :foo</userinput>
3436 This works in both regular SQL commands and meta-commands; there is
3437 more detail in <xref linkend="app-psql-interpolation"
3438 endterm="app-psql-interpolation-title"/>, below.
3442 If you call <command>\set</command> without a second argument, the
3443 variable is set to an empty-string value. To unset (i.e., delete)
3444 a variable, use the command <command>\unset</command>. To show the
3445 values of all variables, call <command>\set</command> without any argument.
3450 The arguments of <command>\set</command> are subject to the same
3451 substitution rules as with other commands. Thus you can construct
3452 interesting references such as <literal>\set :foo
3453 'something'</literal> and get <quote>soft links</quote> or
3454 <quote>variable variables</quote> of <productname>Perl</productname>
3455 or <productname><acronym>PHP</acronym></productname> fame,
3456 respectively. Unfortunately (or fortunately?), there is no way to do
3457 anything useful with these constructs. On the other hand,
3458 <literal>\set bar :foo</literal> is a perfectly valid way to copy a
3464 A number of these variables are treated specially
3465 by <application>psql</application>. They represent certain option
3466 settings that can be changed at run time by altering the value of
3467 the variable, or in some cases represent changeable state of
3468 <application>psql</application>.
3469 By convention, all specially treated variables' names
3470 consist of all upper-case ASCII letters (and possibly digits and
3471 underscores). To ensure maximum compatibility in the future, avoid
3472 using such variable names for your own purposes.
3476 Variables that control <application>psql</application>'s behavior
3477 generally cannot be unset or set to invalid values. An <literal>\unset</literal>
3478 command is allowed but is interpreted as setting the variable to its
3479 default value. A <literal>\set</literal> command without a second argument is
3480 interpreted as setting the variable to <literal>on</literal>, for control
3481 variables that accept that value, and is rejected for others. Also,
3482 control variables that accept the values <literal>on</literal>
3483 and <literal>off</literal> will also accept other common spellings of Boolean
3484 values, such as <literal>true</literal> and <literal>false</literal>.
3488 The specially treated variables are:
3494 <varname>AUTOCOMMIT</varname>
3496 <primary>autocommit</primary>
3497 <secondary>psql</secondary>
3502 When <literal>on</literal> (the default), each SQL command is automatically
3503 committed upon successful completion. To postpone commit in this
3504 mode, you must enter a <command>BEGIN</command> or <command>START
3505 TRANSACTION</command> SQL command. When <literal>off</literal> or unset, SQL
3506 commands are not committed until you explicitly issue
3507 <command>COMMIT</command> or <command>END</command>. The autocommit-off
3508 mode works by issuing an implicit <command>BEGIN</command> for you, just
3509 before any command that is not already in a transaction block and
3510 is not itself a <command>BEGIN</command> or other transaction-control
3511 command, nor a command that cannot be executed inside a transaction
3512 block (such as <command>VACUUM</command>).
3517 In autocommit-off mode, you must explicitly abandon any failed
3518 transaction by entering <command>ABORT</command> or <command>ROLLBACK</command>.
3519 Also keep in mind that if you exit the session
3520 without committing, your work will be lost.
3526 The autocommit-on mode is <productname>PostgreSQL</productname>'s traditional
3527 behavior, but autocommit-off is closer to the SQL spec. If you
3528 prefer autocommit-off, you might wish to set it in the system-wide
3529 <filename>psqlrc</filename> file or your
3530 <filename>~/.psqlrc</filename> file.
3537 <term><varname>COMP_KEYWORD_CASE</varname></term>
3540 Determines which letter case to use when completing an SQL key word.
3541 If set to <literal>lower</literal> or <literal>upper</literal>, the
3542 completed word will be in lower or upper case, respectively. If set
3543 to <literal>preserve-lower</literal>
3544 or <literal>preserve-upper</literal> (the default), the completed word
3545 will be in the case of the word already entered, but words being
3546 completed without anything entered will be in lower or upper case,
3553 <term><varname>DBNAME</varname></term>
3556 The name of the database you are currently connected to. This is
3557 set every time you connect to a database (including program
3558 start-up), but can be changed or unset.
3564 <term><varname>ECHO</varname></term>
3567 If set to <literal>all</literal>, all nonempty input lines are printed
3568 to standard output as they are read. (This does not apply to lines
3569 read interactively.) To select this behavior on program
3570 start-up, use the switch <option>-a</option>. If set to
3571 <literal>queries</literal>,
3572 <application>psql</application> prints each query to standard output
3573 as it is sent to the server. The switch to select this behavior is
3574 <option>-e</option>. If set to <literal>errors</literal>, then only
3575 failed queries are displayed on standard error output. The switch
3576 for this behavior is <option>-b</option>. If set to
3577 <literal>none</literal> (the default), then no queries are displayed.
3583 <term><varname>ECHO_HIDDEN</varname></term>
3586 When this variable is set to <literal>on</literal> and a backslash command
3587 queries the database, the query is first shown.
3588 This feature helps you to study
3589 <productname>PostgreSQL</productname> internals and provide
3590 similar functionality in your own programs. (To select this behavior
3591 on program start-up, use the switch <option>-E</option>.) If you set
3592 this variable to the value <literal>noexec</literal>, the queries are
3593 just shown but are not actually sent to the server and executed.
3594 The default value is <literal>off</literal>.
3600 <term><varname>ENCODING</varname></term>
3603 The current client character set encoding.
3604 This is set every time you connect to a database (including
3605 program start-up), and when you change the encoding
3606 with <literal>\encoding</literal>, but it can be changed or unset.
3612 <term><varname>ERROR</varname></term>
3615 <literal>true</literal> if the last SQL query failed, <literal>false</literal> if
3616 it succeeded. See also <varname>SQLSTATE</varname>.
3622 <term><varname>FETCH_COUNT</varname></term>
3625 If this variable is set to an integer value greater than zero,
3626 the results of <command>SELECT</command> queries are fetched
3627 and displayed in groups of that many rows, rather than the
3628 default behavior of collecting the entire result set before
3629 display. Therefore only a
3630 limited amount of memory is used, regardless of the size of
3631 the result set. Settings of 100 to 1000 are commonly used
3632 when enabling this feature.
3633 Keep in mind that when using this feature, a query might
3634 fail after having already displayed some rows.
3639 Although you can use any output format with this feature,
3640 the default <literal>aligned</literal> format tends to look bad
3641 because each group of <varname>FETCH_COUNT</varname> rows
3642 will be formatted separately, leading to varying column
3643 widths across the row groups. The other output formats work better.
3650 <term><varname>HIDE_TABLEAM</varname></term>
3653 If this variable is set to <literal>true</literal>, a table's access
3654 method details are not displayed. This is mainly useful for
3661 <term><varname>HISTCONTROL</varname></term>
3664 If this variable is set to <literal>ignorespace</literal>,
3665 lines which begin with a space are not entered into the history
3666 list. If set to a value of <literal>ignoredups</literal>, lines
3667 matching the previous history line are not entered. A value of
3668 <literal>ignoreboth</literal> combines the two options. If
3669 set to <literal>none</literal> (the default), all lines
3670 read in interactive mode are saved on the history list.
3674 This feature was shamelessly plagiarized from
3675 <application>Bash</application>.
3682 <term><varname>HISTFILE</varname></term>
3685 The file name that will be used to store the history list. If unset,
3686 the file name is taken from the <envar>PSQL_HISTORY</envar>
3687 environment variable. If that is not set either, the default
3688 is <filename>~/.psql_history</filename>,
3689 or <filename>%APPDATA%\postgresql\psql_history</filename> on Windows.
3690 For example, putting:
3692 \set HISTFILE ~/.psql_history- :DBNAME
3694 in <filename>~/.psqlrc</filename> will cause
3695 <application>psql</application> to maintain a separate history for
3700 This feature was shamelessly plagiarized from
3701 <application>Bash</application>.
3708 <term><varname>HISTSIZE</varname></term>
3711 The maximum number of commands to store in the command history
3712 (default 500). If set to a negative value, no limit is applied.
3716 This feature was shamelessly plagiarized from
3717 <application>Bash</application>.
3724 <term><varname>HOST</varname></term>
3727 The database server host you are currently connected to. This is
3728 set every time you connect to a database (including program
3729 start-up), but can be changed or unset.
3735 <term><varname>IGNOREEOF</varname></term>
3738 If set to 1 or less, sending an <acronym>EOF</acronym> character (usually
3739 <keycombo action="simul"><keycap>Control</keycap><keycap>D</keycap></keycombo>)
3740 to an interactive session of <application>psql</application>
3741 will terminate the application. If set to a larger numeric value,
3742 that many consecutive <acronym>EOF</acronym> characters must be typed to
3743 make an interactive session terminate. If the variable is set to a
3744 non-numeric value, it is interpreted as 10. The default is 0.
3748 This feature was shamelessly plagiarized from
3749 <application>Bash</application>.
3756 <term><varname>LASTOID</varname></term>
3759 The value of the last affected OID, as returned from an
3760 <command>INSERT</command> or <command>\lo_import</command>
3761 command. This variable is only guaranteed to be valid until
3762 after the result of the next <acronym>SQL</acronym> command has
3769 <term><varname>LAST_ERROR_MESSAGE</varname></term>
3770 <term><varname>LAST_ERROR_SQLSTATE</varname></term>
3773 The primary error message and associated SQLSTATE code for the most
3774 recent failed query in the current <application>psql</application> session, or
3775 an empty string and <literal>00000</literal> if no error has occurred in
3776 the current session.
3783 <varname>ON_ERROR_ROLLBACK</varname>
3785 <primary>rollback</primary>
3786 <secondary>psql</secondary>
3791 When set to <literal>on</literal>, if a statement in a transaction block
3792 generates an error, the error is ignored and the transaction
3793 continues. When set to <literal>interactive</literal>, such errors are only
3794 ignored in interactive sessions, and not when reading script
3795 files. When set to <literal>off</literal> (the default), a statement in a
3796 transaction block that generates an error aborts the entire
3797 transaction. The error rollback mode works by issuing an
3798 implicit <command>SAVEPOINT</command> for you, just before each command
3799 that is in a transaction block, and then rolling back to the
3800 savepoint if the command fails.
3806 <term><varname>ON_ERROR_STOP</varname></term>
3809 By default, command processing continues after an error. When this
3810 variable is set to <literal>on</literal>, processing will instead stop
3811 immediately. In interactive mode,
3812 <application>psql</application> will return to the command prompt;
3813 otherwise, <application>psql</application> will exit, returning
3814 error code 3 to distinguish this case from fatal error
3815 conditions, which are reported using error code 1. In either case,
3816 any currently running scripts (the top-level script, if any, and any
3817 other scripts which it may have in invoked) will be terminated
3818 immediately. If the top-level command string contained multiple SQL
3819 commands, processing will stop with the current command.
3825 <term><varname>PORT</varname></term>
3828 The database server port to which you are currently connected.
3829 This is set every time you connect to a database (including
3830 program start-up), but can be changed or unset.
3836 <term><varname>PROMPT1</varname></term>
3837 <term><varname>PROMPT2</varname></term>
3838 <term><varname>PROMPT3</varname></term>
3841 These specify what the prompts <application>psql</application>
3842 issues should look like. See <xref
3843 linkend="app-psql-prompting"
3844 endterm="app-psql-prompting-title"/> below.
3850 <term><varname>QUIET</varname></term>
3853 Setting this variable to <literal>on</literal> is equivalent to the command
3854 line option <option>-q</option>. It is probably not too useful in
3861 <term><varname>ROW_COUNT</varname></term>
3864 The number of rows returned or affected by the last SQL query, or 0
3865 if the query failed or did not report a row count.
3871 <term><varname>SERVER_VERSION_NAME</varname></term>
3872 <term><varname>SERVER_VERSION_NUM</varname></term>
3875 The server's version number as a string, for
3876 example <literal>9.6.2</literal>, <literal>10.1</literal> or <literal>11beta1</literal>,
3877 and in numeric form, for
3878 example <literal>90602</literal> or <literal>100001</literal>.
3879 These are set every time you connect to a database
3880 (including program start-up), but can be changed or unset.
3886 <term><varname>SHOW_CONTEXT</varname></term>
3889 This variable can be set to the
3890 values <literal>never</literal>, <literal>errors</literal>, or <literal>always</literal>
3891 to control whether <literal>CONTEXT</literal> fields are displayed in
3892 messages from the server. The default is <literal>errors</literal> (meaning
3893 that context will be shown in error messages, but not in notice or
3894 warning messages). This setting has no effect
3895 when <varname>VERBOSITY</varname> is set to <literal>terse</literal>
3896 or <literal>sqlstate</literal>.
3897 (See also <command>\errverbose</command>, for use when you want a verbose
3898 version of the error you just got.)
3904 <term><varname>SINGLELINE</varname></term>
3907 Setting this variable to <literal>on</literal> is equivalent to the command
3908 line option <option>-S</option>.
3914 <term><varname>SINGLESTEP</varname></term>
3917 Setting this variable to <literal>on</literal> is equivalent to the command
3918 line option <option>-s</option>.
3924 <term><varname>SQLSTATE</varname></term>
3927 The error code (see <xref linkend="errcodes-appendix"/>) associated
3928 with the last SQL query's failure, or <literal>00000</literal> if it
3935 <term><varname>USER</varname></term>
3938 The database user you are currently connected as. This is set
3939 every time you connect to a database (including program
3940 start-up), but can be changed or unset.
3946 <term><varname>VERBOSITY</varname></term>
3949 This variable can be set to the values <literal>default</literal>,
3950 <literal>verbose</literal>, <literal>terse</literal>,
3951 or <literal>sqlstate</literal> to control the verbosity of error
3953 (See also <command>\errverbose</command>, for use when you want a verbose
3954 version of the error you just got.)
3960 <term><varname>VERSION</varname></term>
3961 <term><varname>VERSION_NAME</varname></term>
3962 <term><varname>VERSION_NUM</varname></term>
3965 These variables are set at program start-up to reflect
3966 <application>psql</application>'s version, respectively as a verbose string,
3967 a short string (e.g., <literal>9.6.2</literal>, <literal>10.1</literal>,
3968 or <literal>11beta1</literal>), and a number (e.g., <literal>90602</literal>
3969 or <literal>100001</literal>). They can be changed or unset.
3978 <refsect3 id="app-psql-interpolation">
3979 <title id="app-psql-interpolation-title"><acronym>SQL</acronym> Interpolation</title>
3982 A key feature of <application>psql</application>
3983 variables is that you can substitute (<quote>interpolate</quote>)
3984 them into regular <acronym>SQL</acronym> statements, as well as the
3985 arguments of meta-commands. Furthermore,
3986 <application>psql</application> provides facilities for
3987 ensuring that variable values used as SQL literals and identifiers are
3988 properly quoted. The syntax for interpolating a value without
3989 any quoting is to prepend the variable name with a colon
3990 (<literal>:</literal>). For example,
3992 testdb=> <userinput>\set foo 'my_table'</userinput>
3993 testdb=> <userinput>SELECT * FROM :foo;</userinput>
3995 would query the table <literal>my_table</literal>. Note that this
3996 may be unsafe: the value of the variable is copied literally, so it can
3997 contain unbalanced quotes, or even backslash commands. You must make sure
3998 that it makes sense where you put it.
4002 When a value is to be used as an SQL literal or identifier, it is
4003 safest to arrange for it to be quoted. To quote the value of
4004 a variable as an SQL literal, write a colon followed by the variable
4005 name in single quotes. To quote the value as an SQL identifier, write
4006 a colon followed by the variable name in double quotes.
4007 These constructs deal correctly with quotes and other special
4008 characters embedded within the variable value.
4009 The previous example would be more safely written this way:
4011 testdb=> <userinput>\set foo 'my_table'</userinput>
4012 testdb=> <userinput>SELECT * FROM :"foo";</userinput>
4017 Variable interpolation will not be performed within quoted
4018 <acronym>SQL</acronym> literals and identifiers. Therefore, a
4019 construction such as <literal>':foo'</literal> doesn't work to produce a quoted
4020 literal from a variable's value (and it would be unsafe if it did work,
4021 since it wouldn't correctly handle quotes embedded in the value).
4025 One example use of this mechanism is to
4026 copy the contents of a file into a table column.
4027 First load the file into a variable and then interpolate the variable's
4028 value as a quoted string:
4030 testdb=> <userinput>\set content `cat my_file.txt`</userinput>
4031 testdb=> <userinput>INSERT INTO my_table VALUES (:'content');</userinput>
4033 (Note that this still won't work if <filename>my_file.txt</filename> contains NUL bytes.
4034 <application>psql</application> does not support embedded NUL bytes in variable values.)
4038 Since colons can legally appear in SQL commands, an apparent attempt
4039 at interpolation (that is, <literal>:name</literal>,
4040 <literal>:'name'</literal>, or <literal>:"name"</literal>) is not
4041 replaced unless the named variable is currently set. In any case, you
4042 can escape a colon with a backslash to protect it from substitution.
4046 The <literal>:{?<replaceable>name</replaceable>}</literal> special syntax returns TRUE
4047 or FALSE depending on whether the variable exists or not, and is thus
4048 always substituted, unless the colon is backslash-escaped.
4052 The colon syntax for variables is standard <acronym>SQL</acronym> for
4053 embedded query languages, such as <application>ECPG</application>.
4054 The colon syntaxes for array slices and type casts are
4055 <productname>PostgreSQL</productname> extensions, which can sometimes
4056 conflict with the standard usage. The colon-quote syntax for escaping a
4057 variable's value as an SQL literal or identifier is a
4058 <application>psql</application> extension.
4063 <refsect3 id="app-psql-prompting">
4064 <title id="app-psql-prompting-title">Prompting</title>
4067 The prompts <application>psql</application> issues can be customized
4068 to your preference. The three variables <varname>PROMPT1</varname>,
4069 <varname>PROMPT2</varname>, and <varname>PROMPT3</varname> contain strings
4070 and special escape sequences that describe the appearance of the
4071 prompt. Prompt 1 is the normal prompt that is issued when
4072 <application>psql</application> requests a new command. Prompt 2 is
4073 issued when more input is expected during command entry, for example
4074 because the command was not terminated with a semicolon or a quote
4076 Prompt 3 is issued when you are running an <acronym>SQL</acronym>
4077 <command>COPY FROM STDIN</command> command and you need to type in
4078 a row value on the terminal.
4082 The value of the selected prompt variable is printed literally,
4083 except where a percent sign (<literal>%</literal>) is encountered.
4084 Depending on the next character, certain other text is substituted
4085 instead. Defined substitutions are:
4089 <term><literal>%M</literal></term>
4092 The full host name (with domain name) of the database server,
4093 or <literal>[local]</literal> if the connection is over a Unix
4095 <literal>[local:<replaceable>/dir/name</replaceable>]</literal>,
4096 if the Unix domain socket is not at the compiled in default
4103 <term><literal>%m</literal></term>
4106 The host name of the database server, truncated at the
4107 first dot, or <literal>[local]</literal> if the connection is
4108 over a Unix domain socket.
4114 <term><literal>%></literal></term>
4115 <listitem><para>The port number at which the database server is listening.</para></listitem>
4119 <term><literal>%n</literal></term>
4122 The database session user name. (The expansion of this
4123 value might change during a database session as the result
4124 of the command <command>SET SESSION
4125 AUTHORIZATION</command>.)
4131 <term><literal>%/</literal></term>
4132 <listitem><para>The name of the current database.</para></listitem>
4136 <term><literal>%~</literal></term>
4137 <listitem><para>Like <literal>%/</literal>, but the output is <literal>~</literal>
4138 (tilde) if the database is your default database.</para></listitem>
4142 <term><literal>%#</literal></term>
4145 If the session user is a database superuser, then a
4146 <literal>#</literal>, otherwise a <literal>></literal>.
4147 (The expansion of this value might change during a database
4148 session as the result of the command <command>SET SESSION
4149 AUTHORIZATION</command>.)
4155 <term><literal>%p</literal></term>
4157 <para>The process ID of the backend currently connected to.</para>
4162 <term><literal>%R</literal></term>
4165 In prompt 1 normally <literal>=</literal>,
4166 but <literal>@</literal> if the session is in an inactive branch of a
4167 conditional block, or <literal>^</literal> if in single-line mode,
4168 or <literal>!</literal> if the session is disconnected from the
4169 database (which can happen if <command>\connect</command> fails).
4170 In prompt 2 <literal>%R</literal> is replaced by a character that
4171 depends on why <application>psql</application> expects more input:
4172 <literal>-</literal> if the command simply wasn't terminated yet,
4173 but <literal>*</literal> if there is an unfinished
4174 <literal>/* ... */</literal> comment,
4175 a single quote if there is an unfinished quoted string,
4176 a double quote if there is an unfinished quoted identifier,
4177 a dollar sign if there is an unfinished dollar-quoted string,
4178 or <literal>(</literal> if there is an unmatched left parenthesis.
4179 In prompt 3 <literal>%R</literal> doesn't produce anything.
4185 <term><literal>%x</literal></term>
4188 Transaction status: an empty string when not in a transaction
4189 block, or <literal>*</literal> when in a transaction block, or
4190 <literal>!</literal> when in a failed transaction block, or <literal>?</literal>
4191 when the transaction state is indeterminate (for example, because
4192 there is no connection).
4198 <term><literal>%l</literal></term>
4201 The line number inside the current statement, starting from <literal>1</literal>.
4207 <term><literal>%</literal><replaceable class="parameter">digits</replaceable></term>
4210 The character with the indicated octal code is substituted.
4216 <term><literal>%:</literal><replaceable class="parameter">name</replaceable><literal>:</literal></term>
4219 The value of the <application>psql</application> variable
4220 <replaceable class="parameter">name</replaceable>. See the
4221 section <xref linkend="app-psql-variables"
4222 endterm="app-psql-variables-title"/> for details.
4228 <term><literal>%`</literal><replaceable class="parameter">command</replaceable><literal>`</literal></term>
4231 The output of <replaceable
4232 class="parameter">command</replaceable>, similar to ordinary
4233 <quote>back-tick</quote> substitution.
4239 <term><literal>%[</literal> ... <literal>%]</literal></term>
4242 Prompts can contain terminal control characters which, for
4243 example, change the color, background, or style of the prompt
4244 text, or change the title of the terminal window. In order for
4245 the line editing features of <application>Readline</application> to work properly, these
4246 non-printing control characters must be designated as invisible
4247 by surrounding them with <literal>%[</literal> and
4248 <literal>%]</literal>. Multiple pairs of these can occur within
4249 the prompt. For example:
4251 testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# '
4253 results in a boldfaced (<literal>1;</literal>) yellow-on-black
4254 (<literal>33;40</literal>) prompt on VT100-compatible, color-capable
4262 To insert a percent sign into your prompt, write
4263 <literal>%%</literal>. The default prompts are
4264 <literal>'%/%R%# '</literal> for prompts 1 and 2, and
4265 <literal>'>> '</literal> for prompt 3.
4270 This feature was shamelessly plagiarized from
4271 <application>tcsh</application>.
4278 <title>Command-Line Editing</title>
4281 <application>psql</application> supports the <application>Readline</application>
4282 library for convenient line editing and retrieval. The command
4283 history is automatically saved when <application>psql</application>
4284 exits and is reloaded when
4285 <application>psql</application> starts up. Tab-completion is also
4286 supported, although the completion logic makes no claim to be an
4287 <acronym>SQL</acronym> parser. The queries generated by tab-completion
4288 can also interfere with other SQL commands, e.g. <literal>SET
4289 TRANSACTION ISOLATION LEVEL</literal>.
4290 If for some reason you do not like the tab completion, you
4291 can turn it off by putting this in a file named
4292 <filename>.inputrc</filename> in your home directory:
4295 set disable-completion on
4298 (This is not a <application>psql</application> but a
4299 <application>Readline</application> feature. Read its documentation
4300 for further details.)
4307 <refsect1 id="app-psql-environment">
4308 <title id="app-psql-environment-title">Environment</title>
4313 <term><envar>COLUMNS</envar></term>
4317 If <literal>\pset columns</literal> is zero, controls the
4318 width for the <literal>wrapped</literal> format and width for determining
4319 if wide output requires the pager or should be switched to the
4320 vertical format in expanded auto mode.
4326 <term><envar>PGDATABASE</envar></term>
4327 <term><envar>PGHOST</envar></term>
4328 <term><envar>PGPORT</envar></term>
4329 <term><envar>PGUSER</envar></term>
4333 Default connection parameters (see <xref linkend="libpq-envars"/>).
4339 <term><envar>PG_COLOR</envar></term>
4342 Specifies whether to use color in diagnostics messages. Possible values
4343 are <literal>always</literal>, <literal>auto</literal>,
4344 <literal>never</literal>.
4350 <term><envar>PSQL_EDITOR</envar></term>
4351 <term><envar>EDITOR</envar></term>
4352 <term><envar>VISUAL</envar></term>
4356 Editor used by the <command>\e</command>, <command>\ef</command>,
4357 and <command>\ev</command> commands.
4358 These variables are examined in the order listed;
4359 the first that is set is used.
4360 If none of them is set, the default is to use <filename>vi</filename>
4361 on Unix systems or <filename>notepad.exe</filename> on Windows systems.
4367 <term><envar>PSQL_EDITOR_LINENUMBER_ARG</envar></term>
4371 When <command>\e</command>, <command>\ef</command>, or
4372 <command>\ev</command> is used
4373 with a line number argument, this variable specifies the
4374 command-line argument used to pass the starting line number to
4375 the user's editor. For editors such as <productname>Emacs</productname> or
4376 <productname>vi</productname>, this is a plus sign. Include a trailing
4377 space in the value of the variable if there needs to be space
4378 between the option name and the line number. Examples:
4380 PSQL_EDITOR_LINENUMBER_ARG='+'
4381 PSQL_EDITOR_LINENUMBER_ARG='--line '
4386 The default is <literal>+</literal> on Unix systems
4387 (corresponding to the default editor <filename>vi</filename>,
4388 and useful for many other common editors); but there is no
4389 default on Windows systems.
4395 <term><envar>PSQL_HISTORY</envar></term>
4399 Alternative location for the command history file. Tilde (<literal>~</literal>) expansion is performed.
4405 <term><envar>PSQL_PAGER</envar></term>
4406 <term><envar>PAGER</envar></term>
4410 If a query's results do not fit on the screen, they are piped
4411 through this command. Typical values are <literal>more</literal>
4412 or <literal>less</literal>.
4413 Use of the pager can be disabled by setting <envar>PSQL_PAGER</envar>
4414 or <envar>PAGER</envar> to an empty string, or by adjusting the
4415 pager-related options of the <command>\pset</command> command.
4416 These variables are examined in the order listed;
4417 the first that is set is used.
4418 If none of them is set, the default is to use <literal>more</literal> on most
4419 platforms, but <literal>less</literal> on Cygwin.
4426 <term><envar>PSQLRC</envar></term>
4430 Alternative location of the user's <filename>.psqlrc</filename> file. Tilde (<literal>~</literal>) expansion is performed.
4436 <term><envar>SHELL</envar></term>
4440 Command executed by the <command>\!</command> command.
4446 <term><envar>TMPDIR</envar></term>
4450 Directory for storing temporary files. The default is
4451 <filename>/tmp</filename>.
4458 This utility, like most other <productname>PostgreSQL</productname> utilities,
4459 also uses the environment variables supported by <application>libpq</application>
4460 (see <xref linkend="libpq-envars"/>).
4467 <title>Files</title>
4471 <term><filename>psqlrc</filename> and <filename>~/.psqlrc</filename></term>
4474 Unless it is passed an <option>-X</option> option,
4475 <application>psql</application> attempts to read and execute commands
4476 from the system-wide startup file (<filename>psqlrc</filename>) and then
4477 the user's personal startup file (<filename>~/.psqlrc</filename>), after
4478 connecting to the database but before accepting normal commands.
4479 These files can be used to set up the client and/or the server to taste,
4480 typically with <command>\set</command> and <command>SET</command>
4484 The system-wide startup file is named <filename>psqlrc</filename> and is
4485 sought in the installation's <quote>system configuration</quote> directory,
4486 which is most reliably identified by running <literal>pg_config
4487 --sysconfdir</literal>. By default this directory will be <filename>../etc/</filename>
4488 relative to the directory containing
4489 the <productname>PostgreSQL</productname> executables. The name of this
4490 directory can be set explicitly via the <envar>PGSYSCONFDIR</envar>
4491 environment variable.
4494 The user's personal startup file is named <filename>.psqlrc</filename>
4495 and is sought in the invoking user's home directory. On Windows, which
4496 lacks such a concept, the personal startup file is named
4497 <filename>%APPDATA%\postgresql\psqlrc.conf</filename>.
4498 The location of the user's startup file can be set explicitly via
4499 the <envar>PSQLRC</envar> environment variable.
4502 Both the system-wide startup file and the user's personal startup file
4503 can be made <application>psql</application>-version-specific
4504 by appending a dash and the <productname>PostgreSQL</productname>
4505 major or minor release number to the file name,
4506 for example <filename>~/.psqlrc-9.2</filename> or
4507 <filename>~/.psqlrc-9.2.5</filename>. The most specific
4508 version-matching file will be read in preference to a
4509 non-version-specific file.
4515 <term><filename>.psql_history</filename></term>
4518 The command-line history is stored in the file
4519 <filename>~/.psql_history</filename>, or
4520 <filename>%APPDATA%\postgresql\psql_history</filename> on Windows.
4523 The location of the history file can be set explicitly via
4524 the <varname>HISTFILE</varname> <application>psql</application> variable or
4525 the <envar>PSQL_HISTORY</envar> environment variable.
4534 <title>Notes</title>
4538 <para><application>psql</application> works best with servers of the same
4539 or an older major version. Backslash commands are particularly likely
4540 to fail if the server is of a newer version than <application>psql</application>
4541 itself. However, backslash commands of the <literal>\d</literal> family should
4542 work with servers of versions back to 7.4, though not necessarily with
4543 servers newer than <application>psql</application> itself. The general
4544 functionality of running SQL commands and displaying query results
4545 should also work with servers of a newer major version, but this cannot
4546 be guaranteed in all cases.
4549 If you want to use <application>psql</application> to connect to several
4550 servers of different major versions, it is recommended that you use the
4551 newest version of <application>psql</application>. Alternatively, you
4552 can keep around a copy of <application>psql</application> from each
4553 major version and be sure to use the version that matches the
4554 respective server. But in practice, this additional complication should
4561 Before <productname>PostgreSQL</productname> 9.6,
4562 the <option>-c</option> option implied <option>-X</option>
4563 (<option>--no-psqlrc</option>); this is no longer the case.
4569 Before <productname>PostgreSQL</productname> 8.4,
4570 <application>psql</application> allowed the
4571 first argument of a single-letter backslash command to start
4572 directly after the command, without intervening whitespace.
4573 Now, some whitespace is required.
4581 <title>Notes for Windows Users</title>
4584 <application>psql</application> is built as a <quote>console
4585 application</quote>. Since the Windows console windows use a different
4586 encoding than the rest of the system, you must take special care
4587 when using 8-bit characters within <application>psql</application>.
4588 If <application>psql</application> detects a problematic
4589 console code page, it will warn you at startup. To change the
4590 console code page, two things are necessary:
4595 Set the code page by entering <userinput>cmd.exe /c chcp
4596 1252</userinput>. (1252 is a code page that is appropriate for
4597 German; replace it with your value.) If you are using Cygwin,
4598 you can put this command in <filename>/etc/profile</filename>.
4604 Set the console font to <literal>Lucida Console</literal>, because the
4605 raster font does not work with the ANSI code page.
4608 </itemizedlist></para>
4613 <refsect1 id="app-psql-examples">
4614 <title id="app-psql-examples-title">Examples</title>
4617 The first example shows how to spread a command over several lines of
4618 input. Notice the changing prompt:
4620 testdb=> <userinput>CREATE TABLE my_table (</userinput>
4621 testdb(> <userinput> first integer not null default 0,</userinput>
4622 testdb(> <userinput> second text)</userinput>
4623 testdb-> <userinput>;</userinput>
4626 Now look at the table definition again:
4628 testdb=> <userinput>\d my_table</userinput>
4629 Table "public.my_table"
4630 Column | Type | Collation | Nullable | Default
4631 --------+---------+-----------+----------+---------
4632 first | integer | | not null | 0
4635 Now we change the prompt to something more interesting:
4637 testdb=> <userinput>\set PROMPT1 '%n@%m %~%R%# '</userinput>
4638 peter@localhost testdb=>
4640 Let's assume you have filled the table with data and want to take a
4643 peter@localhost testdb=> SELECT * FROM my_table;
4653 You can display tables in different ways by using the
4654 <command>\pset</command> command:
4656 peter@localhost testdb=> <userinput>\pset border 2</userinput>
4658 peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput>
4669 peter@localhost testdb=> <userinput>\pset border 0</userinput>
4671 peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput>
4680 peter@localhost testdb=> <userinput>\pset border 1</userinput>
4682 peter@localhost testdb=> <userinput>\pset format csv</userinput>
4683 Output format is csv.
4684 peter@localhost testdb=> <userinput>\pset tuples_only</userinput>
4686 peter@localhost testdb=> <userinput>SELECT second, first FROM my_table;</userinput>
4691 peter@localhost testdb=> <userinput>\pset format unaligned</userinput>
4692 Output format is unaligned.
4693 peter@localhost testdb=> <userinput>\pset fieldsep '\t'</userinput>
4694 Field separator is " ".
4695 peter@localhost testdb=> <userinput>SELECT second, first FROM my_table;</userinput>
4701 Alternatively, use the short commands:
4703 peter@localhost testdb=> <userinput>\a \t \x</userinput>
4704 Output format is aligned.
4706 Expanded display is on.
4707 peter@localhost testdb=> <userinput>SELECT * FROM my_table;</userinput>
4720 </programlisting></para>
4723 When suitable, query results can be shown in a crosstab representation
4724 with the <command>\crosstabview</command> command:
4726 testdb=> <userinput>SELECT first, second, first > 2 AS gt2 FROM my_table;</userinput>
4727 first | second | gt2
4728 -------+--------+-----
4735 testdb=> <userinput>\crosstabview first second</userinput>
4736 first | one | two | three | four
4737 -------+-----+-----+-------+------
4745 This second example shows a multiplication table with rows sorted in reverse
4746 numerical order and columns with an independent, ascending numerical order.
4748 testdb=> <userinput>SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as "AxB",</userinput>
4749 testdb(> <userinput>row_number() over(order by t2.first) AS ord</userinput>
4750 testdb(> <userinput>FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC</userinput>
4751 testdb(> <userinput>\crosstabview "A" "B" "AxB" ord</userinput>
4752 A | 101 | 102 | 103 | 104
4753 ---+-----+-----+-----+-----
4754 4 | 404 | 408 | 412 | 416
4755 3 | 303 | 306 | 309 | 312
4756 2 | 202 | 204 | 206 | 208
4757 1 | 101 | 102 | 103 | 104