4 psql — PostgreSQL interactive terminal
8 psql [option...] [dbname [username]]
12 psql is a terminal-based front-end to PostgreSQL. It enables you to
13 type in queries interactively, issue them to PostgreSQL, and see the
14 query results. Alternatively, input can be from a file or from command
15 line arguments. In addition, psql provides a number of meta-commands
16 and various shell-like features to facilitate writing scripts and
17 automating a wide variety of tasks.
23 Print all nonempty input lines to standard output as they are
24 read. (This does not apply to lines read interactively.) This is
25 equivalent to setting the variable ECHO to all.
29 Switches to unaligned output mode. (The default output mode is
30 aligned.) This is equivalent to \pset format unaligned.
34 Print failed SQL commands to standard error output. This is
35 equivalent to setting the variable ECHO to errors.
39 Specifies that psql is to execute the given command string,
40 command. This option can be repeated and combined in any order
41 with the -f option. When either -c or -f is specified, psql does
42 not read commands from standard input; instead it terminates
43 after processing all the -c and -f options in sequence.
45 command must be either a command string that is completely
46 parsable by the server (i.e., it contains no psql-specific
47 features), or a single backslash command. Thus you cannot mix
48 SQL and psql meta-commands within a -c option. To achieve that,
49 you could use repeated -c options or pipe the string into psql,
52 psql -c '\x' -c 'SELECT * FROM foo;'
56 echo '\x \\ SELECT * FROM foo;' | psql
58 (\\ is the separator meta-command.)
60 Each SQL command string passed to -c is sent to the server as a
61 single request. Because of this, the server executes it as a
62 single transaction even if the string contains multiple SQL
63 commands, unless there are explicit BEGIN/COMMIT commands
64 included in the string to divide it into multiple transactions.
65 (See Section 54.2.2.1 for more details about how the server
66 handles multi-query strings.)
68 If having several commands executed in one transaction is not
69 desired, use repeated -c commands or feed multiple commands to
70 psql's standard input, either using echo as illustrated above,
71 or via a shell here-document, for example:
79 Switches to CSV (Comma-Separated Values) output mode. This is
80 equivalent to \pset format csv.
84 Specifies the name of the database to connect to. This is
85 equivalent to specifying dbname as the first non-option argument
86 on the command line. The dbname can be a connection string. If
87 so, connection string parameters will override any conflicting
92 Copy all SQL commands sent to the server to standard output as
93 well. This is equivalent to setting the variable ECHO to
98 Echo the actual queries generated by \d and other backslash
99 commands. You can use this to study psql's internal operations.
100 This is equivalent to setting the variable ECHO_HIDDEN to on.
104 Read commands from the file filename, rather than standard
105 input. This option can be repeated and combined in any order
106 with the -c option. When either -c or -f is specified, psql does
107 not read commands from standard input; instead it terminates
108 after processing all the -c and -f options in sequence. Except
109 for that, this option is largely equivalent to the meta-command
112 If filename is - (hyphen), then standard input is read until an
113 EOF indication or \q meta-command. This can be used to
114 intersperse interactive input with input from files. Note
115 however that Readline is not used in this case (much as if -n
118 Using this option is subtly different from writing psql <
119 filename. In general, both will do what you expect, but using -f
120 enables some nice features such as error messages with line
121 numbers. There is also a slight chance that using this option
122 will reduce the start-up overhead. On the other hand, the
123 variant using the shell's input redirection is (in theory)
124 guaranteed to yield exactly the same output you would have
125 received had you entered everything by hand.
128 --field-separator=separator #
129 Use separator as the field separator for unaligned output. This
130 is equivalent to \pset fieldsep or \f.
134 Specifies the host name of the machine on which the server is
135 running. If the value begins with a slash, it is used as the
136 directory for the Unix-domain socket.
140 Switches to HTML output mode. This is equivalent to \pset format
141 html or the \H command.
145 List all available databases, then exit. Other non-connection
146 options are ignored. This is similar to the meta-command \list.
148 When this option is used, psql will connect to the database
149 postgres, unless a different database is named on the command
150 line (option -d or non-option argument, possibly via a service
151 entry, but not via an environment variable).
154 --log-file=filename #
155 Write all query output into file filename, in addition to the
156 normal output destination.
160 Do not use Readline for line editing and do not use the command
161 history (see the section called “Command-Line Editing” below).
165 Put all query output into file filename. This is equivalent to
170 Specifies the TCP port or the local Unix-domain socket file
171 extension on which the server is listening for connections.
172 Defaults to the value of the PGPORT environment variable or, if
173 not set, to the port specified at compile time, usually 5432.
177 Specifies printing options, in the style of \pset. Note that
178 here you have to separate name and value with an equal sign
179 instead of a space. For example, to set the output format to
180 LaTeX, you could write -P format=latex.
184 Specifies that psql should do its work quietly. By default, it
185 prints welcome messages and various informational output. If
186 this option is used, none of this happens. This is useful with
187 the -c option. This is equivalent to setting the variable QUIET
191 --record-separator=separator #
192 Use separator as the record separator for unaligned output. This
193 is equivalent to \pset recordsep.
197 Run in single-step mode. That means the user is prompted before
198 each command is sent to the server, with the option to cancel
199 execution as well. Use this to debug scripts.
203 Runs in single-line mode where a newline terminates an SQL
204 command, as a semicolon does.
208 This mode is provided for those who insist on it, but you are
209 not necessarily encouraged to use it. In particular, if you mix
210 SQL and meta-commands on a line the order of execution might not
211 always be clear to the inexperienced user.
215 Turn off printing of column names and result row count footers,
216 etc. This is equivalent to \t or \pset tuples_only.
219 --table-attr=table_options #
220 Specifies options to be placed within the HTML table tag. See
221 \pset tableattr for details.
224 --username=username #
225 Connect to the database as the user username instead of the
226 default. (You must have permission to do so, of course.)
230 --variable=assignment #
231 Perform a variable assignment, like the \set meta-command. Note
232 that you must separate name and value, if any, by an equal sign
233 on the command line. To unset a variable, leave off the equal
234 sign. To set a variable with an empty value, use the equal sign
235 but leave off the value. These assignments are done during
236 command line processing, so variables that reflect connection
237 state will get overwritten later.
241 Print the psql version and exit.
245 Never issue a password prompt. If the server requires password
246 authentication and a password is not available from other
247 sources such as a .pgpass file, the connection attempt will
248 fail. This option can be useful in batch jobs and scripts where
249 no user is present to enter a password.
251 Note that this option will remain set for the entire session,
252 and so it affects uses of the meta-command \connect as well as
253 the initial connection attempt.
257 Force psql to prompt for a password before connecting to a
258 database, even if the password will not be used.
260 If the server requires password authentication and a password is
261 not available from other sources such as a .pgpass file, psql
262 will prompt for a password in any case. However, psql will waste
263 a connection attempt finding out that the server wants a
264 password. In some cases it is worth typing -W to avoid the extra
267 Note that this option will remain set for the entire session,
268 and so it affects uses of the meta-command \connect as well as
269 the initial connection attempt.
273 Turn on the expanded table formatting mode. This is equivalent
274 to \x or \pset expanded.
278 Do not read the start-up file (neither the system-wide psqlrc
279 file nor the user's ~/.psqlrc file).
282 --field-separator-zero #
283 Set the field separator for unaligned output to a zero byte.
284 This is equivalent to \pset fieldsep_zero.
287 --record-separator-zero #
288 Set the record separator for unaligned output to a zero byte.
289 This is useful for interfacing, for example, with xargs -0. This
290 is equivalent to \pset recordsep_zero.
293 --single-transaction #
294 This option can only be used in combination with one or more -c
295 and/or -f options. It causes psql to issue a BEGIN command
296 before the first such option and a COMMIT command after the last
297 one, thereby wrapping all the commands into a single
298 transaction. If any of the commands fails and the variable
299 ON_ERROR_STOP was set, a ROLLBACK command is sent instead. This
300 ensures that either all the commands complete successfully, or
301 no changes are applied.
303 If the commands themselves contain BEGIN, COMMIT, or ROLLBACK,
304 this option will not have the desired effects. Also, if an
305 individual command cannot be executed inside a transaction
306 block, specifying this option will cause the whole transaction
311 Show help about psql and exit. The optional topic parameter
312 (defaulting to options) selects which part of psql is explained:
313 commands describes psql's backslash commands; options describes
314 the command-line options that can be passed to psql; and
315 variables shows help about psql configuration variables.
319 psql returns 0 to the shell if it finished normally, 1 if a fatal error
320 of its own occurs (e.g., out of memory, file not found), 2 if the
321 connection to the server went bad and the session was not interactive,
322 and 3 if an error occurred in a script and the variable ON_ERROR_STOP
327 Connecting to a Database
329 psql is a regular PostgreSQL client application. In order to connect to
330 a database you need to know the name of your target database, the host
331 name and port number of the server, and what database user name you
332 want to connect as. psql can be told about those parameters via command
333 line options, namely -d, -h, -p, and -U respectively. If an argument is
334 found that does not belong to any option it will be interpreted as the
335 database name (or the database user name, if the database name is
336 already given). Not all of these options are required; there are useful
337 defaults. If you omit the host name, psql will connect via a
338 Unix-domain socket to a server on the local host, or via TCP/IP to
339 localhost on Windows. The default port number is determined at compile
340 time. Since the database server uses the same default, you will not
341 have to specify the port in most cases. The default database user name
342 is your operating-system user name. Once the database user name is
343 determined, it is used as the default database name. Note that you
344 cannot just connect to any database under any database user name. Your
345 database administrator should have informed you about your access
348 When the defaults aren't quite right, you can save yourself some typing
349 by setting the environment variables PGDATABASE, PGHOST, PGPORT and/or
350 PGUSER to appropriate values. (For additional environment variables,
351 see Section 32.15.) It is also convenient to have a ~/.pgpass file to
352 avoid regularly having to type in passwords. See Section 32.16 for more
355 An alternative way to specify connection parameters is in a conninfo
356 string or a URI, which is used instead of a database name. This
357 mechanism give you very wide control over the connection. For example:
358 $ psql "service=myservice sslmode=require"
359 $ psql postgresql://dbmaster:5433/mydb?sslmode=require
361 This way you can also use LDAP for connection parameter lookup as
362 described in Section 32.18. See Section 32.1.2 for more information on
363 all the available connection options.
365 If the connection could not be made for any reason (e.g., insufficient
366 privileges, server is not running on the targeted host, etc.), psql
367 will return an error and terminate.
369 If both standard input and standard output are a terminal, then psql
370 sets the client encoding to “auto”, which will detect the appropriate
371 client encoding from the locale settings (LC_CTYPE environment variable
372 on Unix systems). If this doesn't work out as expected, the client
373 encoding can be overridden using the environment variable
376 Entering SQL Commands
378 In normal operation, psql provides a prompt with the name of the
379 database to which psql is currently connected, followed by the string
383 Type "help" for help.
387 At the prompt, the user can type in SQL commands. Ordinarily, input
388 lines are sent to the server when a command-terminating semicolon is
389 reached. An end of line does not terminate a command. Thus commands can
390 be spread over several lines for clarity. If the command was sent and
391 executed without error, the results of the command are displayed on the
394 If untrusted users have access to a database that has not adopted a
395 secure schema usage pattern, begin your session by removing
396 publicly-writable schemas from search_path. One can add
397 options=-csearch_path= to the connection string or issue SELECT
398 pg_catalog.set_config('search_path', '', false) before other SQL
399 commands. This consideration is not specific to psql; it applies to
400 every interface for executing arbitrary SQL commands.
402 Whenever a command is executed, psql also polls for asynchronous
403 notification events generated by LISTEN and NOTIFY.
405 While C-style block comments are passed to the server for processing
406 and removal, SQL-standard comments are removed by psql.
410 Anything you enter in psql that begins with an unquoted backslash is a
411 psql meta-command that is processed by psql itself. These commands make
412 psql more useful for administration or scripting. Meta-commands are
413 often called slash or backslash commands.
415 The format of a psql command is the backslash, followed immediately by
416 a command verb, then any arguments. The arguments are separated from
417 the command verb and each other by any number of whitespace characters.
419 To include whitespace in an argument you can quote it with single
420 quotes. To include a single quote in an argument, write two single
421 quotes within single-quoted text. Anything contained in single quotes
422 is furthermore subject to C-like substitutions for \n (new line), \t
423 (tab), \b (backspace), \r (carriage return), \f (form feed), \digits
424 (octal), and \xdigits (hexadecimal). A backslash preceding any other
425 character within single-quoted text quotes that single character,
428 If an unquoted colon (:) followed by a psql variable name appears
429 within an argument, it is replaced by the variable's value, as
430 described in SQL Interpolation below. The forms :'variable_name' and
431 :"variable_name" described there work as well. The :{?variable_name}
432 syntax allows testing whether a variable is defined. It is substituted
433 by TRUE or FALSE. Escaping the colon with a backslash protects it from
436 Within an argument, text that is enclosed in backquotes (`) is taken as
437 a command line that is passed to the shell. The output of the command
438 (with any trailing newline removed) replaces the backquoted text.
439 Within the text enclosed in backquotes, no special quoting or other
440 processing occurs, except that appearances of :variable_name where
441 variable_name is a psql variable name are replaced by the variable's
442 value. Also, appearances of :'variable_name' are replaced by the
443 variable's value suitably quoted to become a single shell command
444 argument. (The latter form is almost always preferable, unless you are
445 very sure of what is in the variable.) Because carriage return and line
446 feed characters cannot be safely quoted on all platforms, the
447 :'variable_name' form prints an error message and does not substitute
448 the variable value when such characters appear in the value.
450 Some commands take an SQL identifier (such as a table name) as
451 argument. These arguments follow the syntax rules of SQL: Unquoted
452 letters are forced to lowercase, while double quotes (") protect
453 letters from case conversion and allow incorporation of whitespace into
454 the identifier. Within double quotes, paired double quotes reduce to a
455 single double quote in the resulting name. For example, FOO"BAR"BAZ is
456 interpreted as fooBARbaz, and "A weird"" name" becomes A weird" name.
458 Parsing for arguments stops at the end of the line, or when another
459 unquoted backslash is found. An unquoted backslash is taken as the
460 beginning of a new meta-command. The special sequence \\ (two
461 backslashes) marks the end of arguments and continues parsing SQL
462 commands, if any. That way SQL and psql commands can be freely mixed on
463 a line. But in any case, the arguments of a meta-command cannot
464 continue beyond the end of the line.
466 Many of the meta-commands act on the current query buffer. This is
467 simply a buffer holding whatever SQL command text has been typed but
468 not yet sent to the server for execution. This will include previous
469 input lines as well as any text appearing before the meta-command on
472 Many of the meta-commands also allow x to be appended as an option.
473 This will cause the results to be displayed in expanded mode, as if \x
474 or \pset expanded had been used.
476 The following meta-commands are defined:
479 If the current table output format is unaligned, it is switched
480 to aligned. If it is not unaligned, it is set to unaligned. This
481 command is kept for backwards compatibility. See \pset for a
482 more general solution.
484 \bind [ parameter ] ... #
485 Sets query parameters for the next query execution, with the
486 specified parameters passed for any parameter placeholders ($1
491 INSERT INTO tbl1 VALUES ($1, $2) \bind 'first value' 'second value' \g
493 This also works for query-execution commands besides \g, such as
496 This command causes the extended query protocol (see
497 Section 54.1.2) to be used, unlike normal psql operation, which
498 uses the simple query protocol. So this command can be useful to
499 test the extended query protocol from psql. (The extended query
500 protocol is used even if the query has no parameters and this
501 command specifies zero parameters.) This command affects only
502 the next query executed; all subsequent queries will use the
503 simple query protocol by default.
505 \bind_named statement_name [ parameter ] ... #
506 \bind_named is equivalent to \bind, except that it takes the
507 name of an existing prepared statement as first parameter. An
508 empty string denotes the unnamed prepared statement.
512 INSERT INTO tbls1 VALUES ($1, $2) \parse stmt1
513 \bind_named stmt1 'first value' 'second value' \g
515 This command causes the extended query protocol (see
516 Section 54.1.2) to be used, unlike normal psql operation, which
517 uses the simple query protocol. So this command can be useful to
518 test the extended query protocol from psql.
520 \c or \connect [ -reuse-previous=on|off ] [ dbname [ username ] [ host
521 ] [ port ] | conninfo ] #
522 Establishes a new connection to a PostgreSQL server. The
523 connection parameters to use can be specified either using a
524 positional syntax (one or more of database name, user, host, and
525 port), or using a conninfo connection string as detailed in
526 Section 32.1.1. If no arguments are given, a new connection is
527 made using the same parameters as before.
529 Specifying any of dbname, username, host or port as - is
530 equivalent to omitting that parameter.
532 The new connection can re-use connection parameters from the
533 previous connection; not only database name, user, host, and
534 port, but other settings such as sslmode. By default, parameters
535 are re-used in the positional syntax, but not when a conninfo
536 string is given. Passing a first argument of -reuse-previous=on
537 or -reuse-previous=off overrides that default. If parameters are
538 re-used, then any parameter not explicitly specified as a
539 positional parameter or in the conninfo string is taken from the
540 existing connection's parameters. An exception is that if the
541 host setting is changed from its previous value using the
542 positional syntax, any hostaddr setting present in the existing
543 connection's parameters is dropped. Also, any password used for
544 the existing connection will be re-used only if the user, host,
545 and port settings are not changed. When the command neither
546 specifies nor reuses a particular parameter, the libpq default
549 If the new connection is successfully made, the previous
550 connection is closed. If the connection attempt fails (wrong
551 user name, access denied, etc.), the previous connection will be
552 kept if psql is in interactive mode. But when executing a
553 non-interactive script, the old connection is closed and an
554 error is reported. That may or may not terminate the script; if
555 it does not, all database-accessing commands will fail until
556 another \connect command is successfully executed. This
557 distinction was chosen as a user convenience against typos on
558 the one hand, and a safety mechanism that scripts are not
559 accidentally acting on the wrong database on the other hand.
560 Note that whenever a \connect command attempts to re-use
561 parameters, the values re-used are those of the last successful
562 connection, not of any failed attempts made subsequently.
563 However, in the case of a non-interactive \connect failure, no
564 parameters are allowed to be re-used later, since the script
565 would likely be expecting the values from the failed \connect to
570 => \c mydb myuser host.dom 6432
572 => \c "host=localhost port=5432 dbname=mydb connect_timeout=10 sslmode=disable"
573 => \c -reuse-previous=on sslmode=require -- changes only sslmode
574 => \c postgresql://tom@localhost/mydb?application_name=myapp
577 Sets the title of any tables being printed as the result of a
578 query or unset any such title. This command is equivalent to
579 \pset title title. (The name of this command derives from
580 “caption”, as it was previously only used to set the caption in
584 Changes the current working directory to directory. Without
585 argument, changes to the current user's home directory. For
586 details on how home directories are found, see Section 32.16.
590 To print your current working directory, use \! pwd.
592 \close_prepared prepared_statement_name #
593 Closes the specified prepared statement. An empty string denotes
594 the unnamed prepared statement. If no prepared statement exists
595 with this name, the operation is a no-op.
599 SELECT $1 \parse stmt1
600 \close_prepared stmt1
602 This command causes the extended query protocol to be used,
603 unlike normal psql operation, which uses the simple query
604 protocol. So this command can be useful to test the extended
605 query protocol from psql.
608 Outputs information about the current database connection,
609 including SSL-related information if SSL is in use.
611 Note that the Client User field shows the user at the time of
612 connection, while the Superuser field indicates whether the
613 current user (in the current execution context) has superuser
614 privileges. These users are usually the same, but they can
615 differ, for example, if the current user was changed with the
618 \copy { table [ ( column_list ) ] } from { 'filename' | program
619 'command' | stdin | pstdin } [ [ with ] ( option [, ...] ) ] [
621 \copy { table [ ( column_list ) ] | ( query ) } to { 'filename'
622 | program 'command' | stdout | pstdout } [ [ with ] ( option [,
624 Performs a frontend (client) copy. This is an operation that
625 runs an SQL COPY command, but instead of the server reading or
626 writing the specified file, psql reads or writes the file and
627 routes the data between the server and the local file system.
628 This means that file accessibility and privileges are those of
629 the local user, not the server, and no SQL superuser privileges
632 When program is specified, command is executed by psql and the
633 data passed from or to command is routed between the server and
634 the client. Again, the execution privileges are those of the
635 local user, not the server, and no SQL superuser privileges are
638 For \copy ... from stdin, data rows are read from the same
639 source that issued the command, continuing until a line
640 containing only \. is read or the stream reaches EOF. This
641 option is useful for populating tables in-line within an SQL
642 script file. For \copy ... to stdout, output is sent to the same
643 place as psql command output, and the COPY count command status
644 is not printed (since it might be confused with a data row). To
645 read/write psql's standard input or output regardless of the
646 current command source or \o option, write from pstdin or to
649 The syntax of this command is similar to that of the SQL COPY
650 command. All options other than the data source/destination are
651 as specified for COPY. Because of this, special parsing rules
652 apply to the \copy meta-command. Unlike most other
653 meta-commands, the entire remainder of the line is always taken
654 to be the arguments of \copy, and neither variable interpolation
655 nor backquote expansion are performed in the arguments.
659 Another way to obtain the same result as \copy ... to is to use
660 the SQL COPY ... TO STDOUT command and terminate it with \g
661 filename or \g |program. Unlike \copy, this method allows the
662 command to span multiple lines; also, variable interpolation and
663 backquote expansion can be used.
667 These operations are not as efficient as the SQL COPY command
668 with a file or program data source or destination, because all
669 data must pass through the client/server connection. For large
670 amounts of data the SQL command might be preferable.
673 Shows the copyright and distribution terms of PostgreSQL.
675 \crosstabview [ colV [ colH [ colD [ sortcolH ] ] ] ] #
676 Executes the current query buffer (like \g) and shows the
677 results in a crosstab grid. The query must return at least three
678 columns. The output column identified by colV becomes a vertical
679 header and the output column identified by colH becomes a
680 horizontal header. colD identifies the output column to display
681 within the grid. sortcolH identifies an optional sort column for
682 the horizontal header.
684 Each column specification can be a column number (starting at 1)
685 or a column name. The usual SQL case folding and quoting rules
686 apply to column names. If omitted, colV is taken as column 1 and
687 colH as column 2. colH must differ from colV. If colD is not
688 specified, then there must be exactly three columns in the query
689 result, and the column that is neither colV nor colH is taken to
692 The vertical header, displayed as the leftmost column, contains
693 the values found in column colV, in the same order as in the
694 query results, but with duplicates removed.
696 The horizontal header, displayed as the first row, contains the
697 values found in column colH, with duplicates removed. By
698 default, these appear in the same order as in the query results.
699 But if the optional sortcolH argument is given, it identifies a
700 column whose values must be integer numbers, and the values from
701 colH will appear in the horizontal header sorted according to
702 the corresponding sortcolH values.
704 Inside the crosstab grid, for each distinct value x of colH and
705 each distinct value y of colV, the cell located at the
706 intersection (x,y) contains the value of the colD column in the
707 query result row for which the value of colH is x and the value
708 of colV is y. If there is no such row, the cell is empty. If
709 there are multiple such rows, an error is reported.
711 \d[Sx+] [ pattern ] #
712 For each relation (table, view, materialized view, index,
713 sequence, or foreign table) or composite type matching the
714 pattern, show all columns, their types, the tablespace (if not
715 the default) and any special attributes such as NOT NULL or
716 defaults. Associated indexes, constraints, rules, and triggers
717 are also shown. For foreign tables, the associated foreign
718 server is shown as well. (“Matching the pattern” is defined in
721 For some types of relation, \d shows additional information for
722 each column: column values for sequences, indexed expressions
723 for indexes, and foreign data wrapper options for foreign
726 The command form \d+ is identical, except that more information
727 is displayed: any comments associated with the columns of the
728 table are shown, as is the presence of OIDs in the table, the
729 view definition if the relation is a view, a non-default replica
730 identity setting and the access method name if the relation has
733 By default, only user-created objects are shown; supply a
734 pattern or the S modifier to include system objects.
738 If \d is used without a pattern argument, it is equivalent to
739 \dtvmsE which will show a list of all visible tables, views,
740 materialized views, sequences and foreign tables. This is purely
741 a convenience measure.
743 As with many other commands, if x is appended to the command
744 name, the results are displayed in expanded mode, but note that
745 this only applies when \d is used without a pattern argument,
746 and the x modifier cannot appear immediately after the \d
747 (because \dx is a different command); the x modifier may only
748 appear after an S or + modifier. For example, \d+x is equivalent
749 to \dtvmsE+x and will show a list of all relations in expanded
752 \da[Sx] [ pattern ] #
753 Lists aggregate functions, together with their return type and
754 the data types they operate on. If pattern is specified, only
755 aggregates whose names match the pattern are shown. By default,
756 only user-created objects are shown; supply a pattern or the S
757 modifier to include system objects. If x is appended to the
758 command name, the results are displayed in expanded mode.
760 \dA[x+] [ pattern ] #
761 Lists access methods. If pattern is specified, only access
762 methods whose names match the pattern are shown. If x is
763 appended to the command name, the results are displayed in
764 expanded mode. If + is appended to the command name, each access
765 method is listed with its associated handler function and
768 \dAc[x+] [access-method-pattern [input-type-pattern]] #
769 Lists operator classes (see Section 36.16.1). If
770 access-method-pattern is specified, only operator classes
771 associated with access methods whose names match that pattern
772 are listed. If input-type-pattern is specified, only operator
773 classes associated with input types whose names match that
774 pattern are listed. If x is appended to the command name, the
775 results are displayed in expanded mode. If + is appended to the
776 command name, each operator class is listed with its associated
777 operator family and owner.
779 \dAf[x+] [access-method-pattern [input-type-pattern]] #
780 Lists operator families (see Section 36.16.5). If
781 access-method-pattern is specified, only operator families
782 associated with access methods whose names match that pattern
783 are listed. If input-type-pattern is specified, only operator
784 families associated with input types whose names match that
785 pattern are listed. If x is appended to the command name, the
786 results are displayed in expanded mode. If + is appended to the
787 command name, each operator family is listed with its owner.
789 \dAo[x+] [access-method-pattern [operator-family-pattern]] #
790 Lists operators associated with operator families (see
791 Section 36.16.2). If access-method-pattern is specified, only
792 members of operator families associated with access methods
793 whose names match that pattern are listed. If
794 operator-family-pattern is specified, only members of operator
795 families whose names match that pattern are listed. If x is
796 appended to the command name, the results are displayed in
797 expanded mode. If + is appended to the command name, each
798 operator is listed with its sort operator family (if it is an
799 ordering operator), and whether its underlying function is
802 \dAp[x+] [access-method-pattern [operator-family-pattern]] #
803 Lists support functions associated with operator families (see
804 Section 36.16.3). If access-method-pattern is specified, only
805 functions of operator families associated with access methods
806 whose names match that pattern are listed. If
807 operator-family-pattern is specified, only functions of operator
808 families whose names match that pattern are listed. If x is
809 appended to the command name, the results are displayed in
810 expanded mode. If + is appended to the command name, functions
811 are displayed verbosely, with their actual parameter lists.
813 \db[x+] [ pattern ] #
814 Lists tablespaces. If pattern is specified, only tablespaces
815 whose names match the pattern are shown. If x is appended to the
816 command name, the results are displayed in expanded mode. If +
817 is appended to the command name, each tablespace is listed with
818 its associated options, on-disk size, permissions and
821 \dc[Sx+] [ pattern ] #
822 Lists conversions between character-set encodings. If pattern is
823 specified, only conversions whose names match the pattern are
824 listed. By default, only user-created objects are shown; supply
825 a pattern or the S modifier to include system objects. If x is
826 appended to the command name, the results are displayed in
827 expanded mode. If + is appended to the command name, each object
828 is listed with its associated description.
830 \dconfig[x+] [ pattern ] #
831 Lists server configuration parameters and their values. If
832 pattern is specified, only parameters whose names match the
833 pattern are listed. Without a pattern, only parameters that are
834 set to non-default values are listed. (Use \dconfig * to see all
835 parameters.) If x is appended to the command name, the results
836 are displayed in expanded mode. If + is appended to the command
837 name, each parameter is listed with its data type, context in
838 which the parameter can be set, and access privileges (if
839 non-default access privileges have been granted).
841 \dC[x+] [ pattern ] #
842 Lists type casts. If pattern is specified, only casts whose
843 source or target types match the pattern are listed. If x is
844 appended to the command name, the results are displayed in
845 expanded mode. If + is appended to the command name, additional
846 information about each cast is shown, including whether its
847 underlying function is leakproof, and the cast's description.
849 \dd[Sx] [ pattern ] #
850 Shows the descriptions of objects of type constraint, operator
851 class, operator family, rule, and trigger. All other comments
852 may be viewed by the respective backslash commands for those
855 \dd displays descriptions for objects matching the pattern, or
856 of visible objects of the appropriate type if no argument is
857 given. But in either case, only objects that have a description
858 are listed. By default, only user-created objects are shown;
859 supply a pattern or the S modifier to include system objects. If
860 x is appended to the command name, the results are displayed in
863 Descriptions for objects can be created with the COMMENT SQL
866 \dD[Sx+] [ pattern ] #
867 Lists domains. If pattern is specified, only domains whose names
868 match the pattern are shown. By default, only user-created
869 objects are shown; supply a pattern or the S modifier to include
870 system objects. If x is appended to the command name, the
871 results are displayed in expanded mode. If + is appended to the
872 command name, each object is listed with its associated
873 permissions and description.
875 \ddp[x] [ pattern ] #
876 Lists default access privilege settings. An entry is shown for
877 each role (and schema, if applicable) for which the default
878 privilege settings have been changed from the built-in defaults.
879 If pattern is specified, only entries whose role name or schema
880 name matches the pattern are listed. If x is appended to the
881 command name, the results are displayed in expanded mode.
883 The ALTER DEFAULT PRIVILEGES command is used to set default
884 access privileges. The meaning of the privilege display is
885 explained in Section 5.8.
892 \dv[Sx+] [ pattern ] #
893 In this group of commands, the letters E, i, m, s, t, and v
894 stand for foreign table, index, materialized view, sequence,
895 table, and view, respectively. You can specify any or all of
896 these letters, in any order, to obtain a listing of objects of
897 these types. For example, \dti lists tables and indexes. If x is
898 appended to the command name, the results are displayed in
899 expanded mode. If + is appended to the command name, each object
900 is listed with its persistence status (permanent, temporary, or
901 unlogged), physical size on disk, and associated description if
902 any. If pattern is specified, only objects whose names match the
903 pattern are listed. By default, only user-created objects are
904 shown; supply a pattern or the S modifier to include system
907 \des[x+] [ pattern ] #
908 Lists foreign servers (mnemonic: “external servers”). If pattern
909 is specified, only those servers whose name matches the pattern
910 are listed. If x is appended to the command name, the results
911 are displayed in expanded mode. If + is appended to the command
912 name, a full description of each server is shown, including the
913 server's access privileges, type, version, options, and
916 \det[x+] [ pattern ] #
917 Lists foreign tables (mnemonic: “external tables”). If pattern
918 is specified, only entries whose table name or schema name
919 matches the pattern are listed. If x is appended to the command
920 name, the results are displayed in expanded mode. If + is
921 appended to the command name, generic options and the foreign
922 table description are also displayed.
924 \deu[x+] [ pattern ] #
925 Lists user mappings (mnemonic: “external users”). If pattern is
926 specified, only those mappings whose user names match the
927 pattern are listed. If x is appended to the command name, the
928 results are displayed in expanded mode. If + is appended to the
929 command name, additional information about each mapping is
934 \deu+ might also display the user name and password of the
935 remote user, so care should be taken not to disclose them.
937 \dew[x+] [ pattern ] #
938 Lists foreign-data wrappers (mnemonic: “external wrappers”). If
939 pattern is specified, only those foreign-data wrappers whose
940 name matches the pattern are listed. If x is appended to the
941 command name, the results are displayed in expanded mode. If +
942 is appended to the command name, the access privileges, options,
943 and description of the foreign-data wrapper are also shown.
945 \df[anptwSx+] [ pattern [ arg_pattern ... ] ] #
946 Lists functions, together with their result data types, argument
947 data types, and function types, which are classified as “agg”
948 (aggregate), “normal”, “procedure”, “trigger”, or “window”. To
949 display only functions of specific type(s), add the
950 corresponding letters a, n, p, t, or w to the command. If
951 pattern is specified, only functions whose names match the
952 pattern are shown. Any additional arguments are type-name
953 patterns, which are matched to the type names of the first,
954 second, and so on arguments of the function. (Matching functions
955 can have more arguments than what you specify. To prevent that,
956 write a dash - as the last arg_pattern.) By default, only
957 user-created objects are shown; supply a pattern or the S
958 modifier to include system objects. If x is appended to the
959 command name, the results are displayed in expanded mode. If +
960 is appended to the command name, additional information about
961 each function is shown, including volatility, parallel safety,
962 owner, security classification, whether it is leakproof, access
963 privileges, language, internal name (for C and internal
964 functions only), and description. Source code for a specific
965 function can be seen using \sf.
967 \dF[x+] [ pattern ] #
968 Lists text search configurations. If pattern is specified, only
969 configurations whose names match the pattern are shown. If x is
970 appended to the command name, the results are displayed in
971 expanded mode. If + is appended to the command name, a full
972 description of each configuration is shown, including the
973 underlying text search parser and the dictionary list for each
976 \dFd[x+] [ pattern ] #
977 Lists text search dictionaries. If pattern is specified, only
978 dictionaries whose names match the pattern are shown. If x is
979 appended to the command name, the results are displayed in
980 expanded mode. If + is appended to the command name, additional
981 information is shown about each selected dictionary, including
982 the underlying text search template and the option values.
984 \dFp[x+] [ pattern ] #
985 Lists text search parsers. If pattern is specified, only parsers
986 whose names match the pattern are shown. If x is appended to the
987 command name, the results are displayed in expanded mode. If +
988 is appended to the command name, a full description of each
989 parser is shown, including the underlying functions and the list
990 of recognized token types.
992 \dFt[x+] [ pattern ] #
993 Lists text search templates. If pattern is specified, only
994 templates whose names match the pattern are shown. If x is
995 appended to the command name, the results are displayed in
996 expanded mode. If + is appended to the command name, additional
997 information is shown about each template, including the
998 underlying function names.
1000 \dg[Sx+] [ pattern ] #
1001 Lists database roles. (Since the concepts of “users” and
1002 “groups” have been unified into “roles”, this command is now
1003 equivalent to \du.) By default, only user-created roles are
1004 shown; supply the S modifier to include system roles. If pattern
1005 is specified, only those roles whose names match the pattern are
1006 listed. If x is appended to the command name, the results are
1007 displayed in expanded mode. If + is appended to the command
1008 name, additional information is shown about each role; currently
1009 this adds the comment for each role.
1012 This is an alias for \lo_list, which shows a list of large
1013 objects. If x is appended to the command name, the results are
1014 displayed in expanded mode. If + is appended to the command
1015 name, each large object is listed with its associated
1016 permissions, if any.
1018 \dL[Sx+] [ pattern ] #
1019 Lists procedural languages. If pattern is specified, only
1020 languages whose names match the pattern are listed. By default,
1021 only user-created languages are shown; supply the S modifier to
1022 include system objects. If x is appended to the command name,
1023 the results are displayed in expanded mode. If + is appended to
1024 the command name, each language is listed with its call handler,
1025 validator, access privileges, and whether it is a system object.
1027 \dn[Sx+] [ pattern ] #
1028 Lists schemas (namespaces). If pattern is specified, only
1029 schemas whose names match the pattern are listed. By default,
1030 only user-created objects are shown; supply a pattern or the S
1031 modifier to include system objects. If x is appended to the
1032 command name, the results are displayed in expanded mode. If +
1033 is appended to the command name, each object is listed with its
1034 associated permissions and description, if any.
1036 \do[Sx+] [ pattern [ arg_pattern [ arg_pattern ] ] ] #
1037 Lists operators with their operand and result types. If pattern
1038 is specified, only operators whose names match the pattern are
1039 listed. If one arg_pattern is specified, only prefix operators
1040 whose right argument's type name matches that pattern are
1041 listed. If two arg_patterns are specified, only binary operators
1042 whose argument type names match those patterns are listed.
1043 (Alternatively, write - for the unused argument of a unary
1044 operator.) By default, only user-created objects are shown;
1045 supply a pattern or the S modifier to include system objects. If
1046 x is appended to the command name, the results are displayed in
1047 expanded mode. If + is appended to the command name, additional
1048 information about each operator is shown, including the name of
1049 the underlying function, and whether it is leakproof.
1051 \dO[Sx+] [ pattern ] #
1052 Lists collations. If pattern is specified, only collations whose
1053 names match the pattern are listed. By default, only
1054 user-created objects are shown; supply a pattern or the S
1055 modifier to include system objects. If x is appended to the
1056 command name, the results are displayed in expanded mode. If +
1057 is appended to the command name, each collation is listed with
1058 its associated description, if any. Note that only collations
1059 usable with the current database's encoding are shown, so the
1060 results may vary in different databases of the same
1063 \dp[Sx] [ pattern ] #
1064 Lists tables, views and sequences with their associated access
1065 privileges. If pattern is specified, only tables, views and
1066 sequences whose names match the pattern are listed. By default
1067 only user-created objects are shown; supply a pattern or the S
1068 modifier to include system objects. If x is appended to the
1069 command name, the results are displayed in expanded mode.
1071 The GRANT and REVOKE commands are used to set access privileges.
1072 The meaning of the privilege display is explained in
1075 \dP[itnx+] [ pattern ] #
1076 Lists partitioned relations. If pattern is specified, only
1077 entries whose name matches the pattern are listed. The modifiers
1078 t (tables) and i (indexes) can be appended to the command,
1079 filtering the kind of relations to list. By default, partitioned
1080 tables and indexes are listed.
1082 If the modifier n (“nested”) is used, or a pattern is specified,
1083 then non-root partitioned relations are included, and a column
1084 is shown displaying the parent of each partitioned relation.
1086 If x is appended to the command name, the results are displayed
1087 in expanded mode. If + is appended to the command name, the sum
1088 of the sizes of each relation's partitions is also displayed,
1089 along with the relation's description. If n is combined with +,
1090 two sizes are shown: one including the total size of
1091 directly-attached leaf partitions, and another showing the total
1092 size of all partitions, including indirectly attached
1095 \drds[x] [ role-pattern [ database-pattern ] ] #
1096 Lists defined configuration settings. These settings can be
1097 role-specific, database-specific, or both. role-pattern and
1098 database-pattern are used to select specific roles and databases
1099 to list, respectively. If omitted, or if * is specified, all
1100 settings are listed, including those not role-specific or
1101 database-specific, respectively. If x is appended to the command
1102 name, the results are displayed in expanded mode.
1104 The ALTER ROLE and ALTER DATABASE commands are used to define
1105 per-role and per-database configuration settings.
1107 \drg[Sx] [ pattern ] #
1108 Lists information about each granted role membership, including
1109 assigned options (ADMIN, INHERIT and/or SET) and grantor. See
1110 the GRANT command for information about role memberships.
1112 By default, only grants to user-created roles are shown; supply
1113 the S modifier to include system roles. If pattern is specified,
1114 only grants to those roles whose names match the pattern are
1115 listed. If x is appended to the command name, the results are
1116 displayed in expanded mode.
1118 \dRp[x+] [ pattern ] #
1119 Lists replication publications. If pattern is specified, only
1120 those publications whose names match the pattern are listed. If
1121 x is appended to the command name, the results are displayed in
1122 expanded mode. If + is appended to the command name, the tables
1123 and schemas associated with each publication are shown as well.
1125 \dRs[x+] [ pattern ] #
1126 Lists replication subscriptions. If pattern is specified, only
1127 those subscriptions whose names match the pattern are listed. If
1128 x is appended to the command name, the results are displayed in
1129 expanded mode. If + is appended to the command name, additional
1130 properties of the subscriptions are shown.
1132 \dT[Sx+] [ pattern ] #
1133 Lists data types. If pattern is specified, only types whose
1134 names match the pattern are listed. If x is appended to the
1135 command name, the results are displayed in expanded mode. If +
1136 is appended to the command name, each type is listed with its
1137 internal name and size, its allowed values if it is an enum
1138 type, and its associated permissions. By default, only
1139 user-created objects are shown; supply a pattern or the S
1140 modifier to include system objects.
1142 \du[Sx+] [ pattern ] #
1143 Lists database roles. (Since the concepts of “users” and
1144 “groups” have been unified into “roles”, this command is now
1145 equivalent to \dg.) By default, only user-created roles are
1146 shown; supply the S modifier to include system roles. If pattern
1147 is specified, only those roles whose names match the pattern are
1148 listed. If x is appended to the command name, the results are
1149 displayed in expanded mode. If + is appended to the command
1150 name, additional information is shown about each role; currently
1151 this adds the comment for each role.
1153 \dx[x+] [ pattern ] #
1154 Lists installed extensions. If pattern is specified, only those
1155 extensions whose names match the pattern are listed. If x is
1156 appended to the command name, the results are displayed in
1157 expanded mode. If + is appended to the command name, all the
1158 objects belonging to each matching extension are listed.
1160 \dX[x] [ pattern ] #
1161 Lists extended statistics. If pattern is specified, only those
1162 extended statistics whose names match the pattern are listed. If
1163 x is appended to the command name, the results are displayed in
1166 The status of each kind of extended statistics is shown in a
1167 column named after its statistic kind (e.g. Ndistinct). defined
1168 means that it was requested when creating the statistics, and
1169 NULL means it wasn't requested. You can use pg_stats_ext if
1170 you'd like to know whether ANALYZE was run and statistics are
1171 available to the planner.
1173 \dy[x+] [ pattern ] #
1174 Lists event triggers. If pattern is specified, only those event
1175 triggers whose names match the pattern are listed. If x is
1176 appended to the command name, the results are displayed in
1177 expanded mode. If + is appended to the command name, each object
1178 is listed with its associated description.
1180 \e or \edit [ filename ] [ line_number ] #
1181 If filename is specified, the file is edited; after the editor
1182 exits, the file's content is copied into the current query
1183 buffer. If no filename is given, the current query buffer is
1184 copied to a temporary file which is then edited in the same
1185 fashion. Or, if the current query buffer is empty, the most
1186 recently executed query is copied to a temporary file and edited
1187 in the same fashion.
1189 If you edit a file or the previous query, and you quit the
1190 editor without modifying the file, the query buffer is cleared.
1191 Otherwise, the new contents of the query buffer are re-parsed
1192 according to the normal rules of psql, treating the whole buffer
1193 as a single line. Any complete queries are immediately executed;
1194 that is, if the query buffer contains or ends with a semicolon,
1195 everything up to that point is executed and removed from the
1196 query buffer. Whatever remains in the query buffer is
1197 redisplayed. Type semicolon or \g to send it, or \r to cancel it
1198 by clearing the query buffer.
1200 Treating the buffer as a single line primarily affects
1201 meta-commands: whatever is in the buffer after a meta-command
1202 will be taken as argument(s) to the meta-command, even if it
1203 spans multiple lines. (Thus you cannot make meta-command-using
1204 scripts this way. Use \i for that.)
1206 If a line number is specified, psql will position the cursor on
1207 the specified line of the file or query buffer. Note that if a
1208 single all-digits argument is given, psql assumes it is a line
1209 number, not a file name.
1213 See Environment, below, for how to configure and customize your
1216 \echo text [ ... ] #
1217 Prints the evaluated arguments to standard output, separated by
1218 spaces and followed by a newline. This can be useful to
1219 intersperse information in the output of scripts. For example:
1222 Tue Oct 26 21:40:57 CEST 1999
1224 If the first argument is an unquoted -n the trailing newline is
1225 not written (nor is the first argument).
1229 If you use the \o command to redirect your query output you
1230 might wish to use \qecho instead of this command. See also
1233 \ef [ function_description [ line_number ] ] #
1234 This command fetches and edits the definition of the named
1235 function or procedure, in the form of a CREATE OR REPLACE
1236 FUNCTION or CREATE OR REPLACE PROCEDURE command. Editing is done
1237 in the same way as for \edit. If you quit the editor without
1238 saving, the statement is discarded. If you save and exit the
1239 editor, the updated command is executed immediately if you added
1240 a semicolon to it. Otherwise it is redisplayed; type semicolon
1241 or \g to send it, or \r to cancel.
1243 The target function can be specified by name alone, or by name
1244 and arguments, for example foo(integer, text). The argument
1245 types must be given if there is more than one function of the
1248 If no function is specified, a blank CREATE FUNCTION template is
1249 presented for editing.
1251 If a line number is specified, psql will position the cursor on
1252 the specified line of the function body. (Note that the function
1253 body typically does not begin on the first line of the file.)
1255 Unlike most other meta-commands, the entire remainder of the
1256 line is always taken to be the argument(s) of \ef, and neither
1257 variable interpolation nor backquote expansion are performed in
1262 See Environment, below, for how to configure and customize your
1265 \encoding [ encoding ] #
1266 Sets the client character set encoding. Without an argument,
1267 this command shows the current encoding.
1270 Repeats the most recent server error message at maximum
1271 verbosity, as though VERBOSITY were set to verbose and
1272 SHOW_CONTEXT were set to always.
1274 \ev [ view_name [ line_number ] ] #
1275 This command fetches and edits the definition of the named view,
1276 in the form of a CREATE OR REPLACE VIEW command. Editing is done
1277 in the same way as for \edit. If you quit the editor without
1278 saving, the statement is discarded. If you save and exit the
1279 editor, the updated command is executed immediately if you added
1280 a semicolon to it. Otherwise it is redisplayed; type semicolon
1281 or \g to send it, or \r to cancel.
1283 If no view is specified, a blank CREATE VIEW template is
1284 presented for editing.
1286 If a line number is specified, psql will position the cursor on
1287 the specified line of the view definition.
1289 Unlike most other meta-commands, the entire remainder of the
1290 line is always taken to be the argument(s) of \ev, and neither
1291 variable interpolation nor backquote expansion are performed in
1295 Sets the field separator for unaligned query output. The default
1296 is the vertical bar (|). It is equivalent to \pset fieldsep.
1298 \g [ (option=value [...]) ] [ filename ]
1299 \g [ (option=value [...]) ] [ |command ] #
1300 Sends the current query buffer to the server for execution.
1302 If parentheses appear after \g, they surround a space-separated
1303 list of option=value formatting-option clauses, which are
1304 interpreted in the same way as \pset option value commands, but
1305 take effect only for the duration of this query. In this list,
1306 spaces are not allowed around = signs, but are required between
1307 option clauses. If =value is omitted, the named option is
1308 changed in the same way as for \pset option with no explicit
1311 If a filename or |command argument is given, the query's output
1312 is written to the named file or piped to the given shell
1313 command, instead of displaying it as usual. The file or command
1314 is written to only if the query successfully returns zero or
1315 more tuples, not if the query fails or is a non-data-returning
1318 If the current query buffer is empty, the most recently sent
1319 query is re-executed instead. Except for that behavior, \g
1320 without any arguments is essentially equivalent to a semicolon.
1321 With arguments, \g provides a “one-shot” alternative to the \o
1322 command, and additionally allows one-shot adjustments of the
1323 output formatting options normally set by \pset.
1325 When the last argument begins with |, the entire remainder of
1326 the line is taken to be the command to execute, and neither
1327 variable interpolation nor backquote expansion are performed in
1328 it. The rest of the line is simply passed literally to the
1332 Shows the description (that is, the column names and data types)
1333 of the result of the current query buffer. The query is not
1334 actually executed; however, if it contains some type of syntax
1335 error, that error will be reported in the normal way.
1337 If the current query buffer is empty, the most recently sent
1338 query is described instead.
1340 \getenv psql_var env_var #
1341 Gets the value of the environment variable env_var and assigns
1342 it to the psql variable psql_var. If env_var is not defined in
1343 the psql process's environment, psql_var is not changed.
1346 => \getenv home HOME
1351 Sends the current query buffer to the server, then treats each
1352 column of each row of the query's output (if any) as an SQL
1353 statement to be executed. For example, to create an index on
1354 each column of my_table:
1356 => SELECT format('create index on my_table(%I)', attname)
1357 -> FROM pg_attribute
1358 -> WHERE attrelid = 'my_table'::regclass AND attnum > 0
1366 The generated queries are executed in the order in which the
1367 rows are returned, and left-to-right within each row if there is
1368 more than one column. NULL fields are ignored. The generated
1369 queries are sent literally to the server for processing, so they
1370 cannot be psql meta-commands nor contain psql variable
1371 references. If any individual query fails, execution of the
1372 remaining queries continues unless ON_ERROR_STOP is set.
1373 Execution of each query is subject to ECHO processing. (Setting
1374 ECHO to all or queries is often advisable when using \gexec.)
1375 Query logging, single-step mode, timing, and other query
1376 execution features apply to each generated query as well.
1378 If the current query buffer is empty, the most recently sent
1379 query is re-executed instead.
1382 Sends the current query buffer to the server and stores the
1383 query's output into psql variables (see Variables below). The
1384 query to be executed must return exactly one row. Each column of
1385 the row is stored into a separate variable, named the same as
1386 the column. For example:
1388 => SELECT 'hello' AS var1, 10 AS var2
1390 => \echo :var1 :var2
1393 If you specify a prefix, that string is prepended to the query's
1394 column names to create the variable names to use:
1396 => SELECT 'hello' AS var1, 10 AS var2
1398 => \echo :result_var1 :result_var2
1401 If a column result is NULL, the corresponding variable is unset
1402 rather than being set.
1404 If the query fails or does not return one row, no variables are
1407 If the current query buffer is empty, the most recently sent
1408 query is re-executed instead.
1410 \gx [ (option=value [...]) ] [ filename ]
1411 \gx [ (option=value [...]) ] [ |command ] #
1412 \gx is equivalent to \g, except that it forces expanded output
1413 mode for this query, as if expanded=on were included in the list
1414 of \pset options. See also \x.
1416 \h or \help [ command ] #
1417 Gives syntax help on the specified SQL command. If command is
1418 not specified, then psql will list all the commands for which
1419 syntax help is available. If command is an asterisk (*), then
1420 syntax help on all SQL commands is shown.
1422 Unlike most other meta-commands, the entire remainder of the
1423 line is always taken to be the argument(s) of \help, and neither
1424 variable interpolation nor backquote expansion are performed in
1429 To simplify typing, commands that consists of several words do
1430 not have to be quoted. Thus it is fine to type \help alter
1434 Turns on HTML query output format. If the HTML format is already
1435 on, it is switched back to the default aligned text format. This
1436 command is for compatibility and convenience, but see \pset
1437 about setting other output options.
1439 \i or \include filename #
1440 Reads input from the file filename and executes it as though it
1441 had been typed on the keyboard.
1443 If filename is - (hyphen), then standard input is read until an
1444 EOF indication or \q meta-command. This can be used to
1445 intersperse interactive input with input from files. Note that
1446 Readline behavior will be used only if it is active at the
1451 If you want to see the lines on the screen as they are read you
1452 must set the variable ECHO to all.
1458 This group of commands implements nestable conditional blocks. A
1459 conditional block must begin with an \if and end with an \endif.
1460 In between there may be any number of \elif clauses, which may
1461 optionally be followed by a single \else clause. Ordinary
1462 queries and other types of backslash commands may (and usually
1463 do) appear between the commands forming a conditional block.
1465 The \if and \elif commands read their argument(s) and evaluate
1466 them as a Boolean expression. If the expression yields true then
1467 processing continues normally; otherwise, lines are skipped
1468 until a matching \elif, \else, or \endif is reached. Once an \if
1469 or \elif test has succeeded, the arguments of later \elif
1470 commands in the same block are not evaluated but are treated as
1471 false. Lines following an \else are processed only if no earlier
1472 matching \if or \elif succeeded.
1474 The expression argument of an \if or \elif command is subject to
1475 variable interpolation and backquote expansion, just like any
1476 other backslash command argument. After that it is evaluated
1477 like the value of an on/off option variable. So a valid value is
1478 any unambiguous case-insensitive match for one of: true, false,
1479 1, 0, on, off, yes, no. For example, t, T, and tR will all be
1480 considered to be true.
1482 Expressions that do not properly evaluate to true or false will
1483 generate a warning and be treated as false.
1485 Lines being skipped are parsed normally to identify queries and
1486 backslash commands, but queries are not sent to the server, and
1487 backslash commands other than conditionals (\if, \elif, \else,
1488 \endif) are ignored. Conditional commands are checked only for
1489 valid nesting. Variable references in skipped lines are not
1490 expanded, and backquote expansion is not performed either.
1492 All the backslash commands of a given conditional block must
1493 appear in the same source file. If EOF is reached on the main
1494 input file or an \include-ed file before all local \if-blocks
1495 have been closed, then psql will raise an error.
1499 -- check for the existence of two separate records in the database and store
1500 -- the results in separate psql variables
1502 EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer,
1503 EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee
1506 SELECT * FROM customer WHERE customer_id = 123;
1508 \echo 'is not a customer but is an employee'
1509 SELECT * FROM employee WHERE employee_id = 456;
1512 \echo 'not a customer or employee'
1514 \echo 'this will never print'
1518 \ir or \include_relative filename #
1519 The \ir command is similar to \i, but resolves relative file
1520 names differently. When executing in interactive mode, the two
1521 commands behave identically. However, when invoked from a
1522 script, \ir interprets file names relative to the directory in
1523 which the script is located, rather than the current working
1526 \l[x+] or \list[x+] [ pattern ] #
1527 List the databases in the server and show their names, owners,
1528 character set encodings, and access privileges. If pattern is
1529 specified, only databases whose names match the pattern are
1530 listed. If x is appended to the command name, the results are
1531 displayed in expanded mode. If + is appended to the command
1532 name, database sizes, default tablespaces, and descriptions are
1533 also displayed. (Size information is only available for
1534 databases that the current user can connect to.)
1536 \lo_export loid filename #
1537 Reads the large object with OID loid from the database and
1538 writes it to filename. Note that this is subtly different from
1539 the server function lo_export, which acts with the permissions
1540 of the user that the database server runs as and on the server's
1545 Use \lo_list to find out the large object's OID.
1547 \lo_import filename [ comment ] #
1548 Stores the file into a PostgreSQL large object. Optionally, it
1549 associates the given comment with the object. Example:
1551 foo=> \lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'
1554 The response indicates that the large object received object ID
1555 152801, which can be used to access the newly-created large
1556 object in the future. For the sake of readability, it is
1557 recommended to always associate a human-readable comment with
1558 every object. Both OIDs and comments can be viewed with the
1561 Note that this command is subtly different from the server-side
1562 lo_import because it acts as the local user on the local file
1563 system, rather than the server's user and file system.
1566 Shows a list of all PostgreSQL large objects currently stored in
1567 the database, along with any comments provided for them. If x is
1568 appended to the command name, the results are displayed in
1569 expanded mode. If + is appended to the command name, each large
1570 object is listed with its associated permissions, if any.
1573 Deletes the large object with OID loid from the database.
1577 Use \lo_list to find out the large object's OID.
1579 \o or \out [ filename ]
1580 \o or \out [ |command ] #
1581 Arranges to save future query results to the file filename or
1582 pipe future results to the shell command command. If no argument
1583 is specified, the query output is reset to the standard output.
1585 If the argument begins with |, then the entire remainder of the
1586 line is taken to be the command to execute, and neither variable
1587 interpolation nor backquote expansion are performed in it. The
1588 rest of the line is simply passed literally to the shell.
1590 “Query results” includes all tables, command responses, and
1591 notices obtained from the database server, as well as output of
1592 various backslash commands that query the database (such as \d);
1593 but not error messages.
1597 To intersperse text output in between query results, use \qecho.
1600 Print the current query buffer to the standard output. If the
1601 current query buffer is empty, the most recently executed query
1604 \parse statement_name #
1605 Creates a prepared statement from the current query buffer,
1606 based on the name of a destination prepared-statement object. An
1607 empty string denotes the unnamed prepared statement.
1611 SELECT $1 \parse stmt1
1613 This command causes the extended query protocol to be used,
1614 unlike normal psql operation, which uses the simple query
1615 protocol. A Parse (F) message will be issued by this command so
1616 it can be useful to test the extended query protocol from psql.
1617 This command affects only the next query executed; all
1618 subsequent queries will use the simple query protocol by
1621 \password [ username ] #
1622 Changes the password of the specified user (by default, the
1623 current user). This command prompts for the new password,
1624 encrypts it, and sends it to the server as an ALTER ROLE
1625 command. This makes sure that the new password does not appear
1626 in cleartext in the command history, the server log, or
1629 \prompt [ text ] name #
1630 Prompts the user to supply text, which is assigned to the
1631 variable name. An optional prompt string, text, can be
1632 specified. (For multiword prompts, surround the text with single
1635 By default, \prompt uses the terminal for input and output.
1636 However, if the -f command line switch was used, \prompt uses
1637 standard input and standard output.
1639 \pset [ option [ value ] ] #
1640 This command sets options affecting the output of query result
1641 tables. option indicates which option is to be set. The
1642 semantics of value vary depending on the selected option. For
1643 some options, omitting value causes the option to be toggled or
1644 unset, as described under the particular option. If no such
1645 behavior is mentioned, then omitting value just results in the
1646 current setting being displayed.
1648 \pset without any arguments displays the current status of all
1651 Adjustable printing options are:
1654 The value must be a number. In general, the higher the
1655 number the more borders and lines the tables will have,
1656 but details depend on the particular format. In HTML
1657 format, this will translate directly into the border=...
1658 attribute. In most other formats only values 0 (no
1659 border), 1 (internal dividing lines), and 2 (table frame)
1660 make sense, and values above 2 will be treated the same as
1661 border = 2. The latex and latex-longtable formats
1662 additionally allow a value of 3 to add dividing lines
1666 Sets the target width for the wrapped format, and also the
1667 width limit for determining whether output is wide enough
1668 to require the pager or switch to the vertical display in
1669 expanded auto mode. Zero (the default) causes the target
1670 width to be controlled by the environment variable
1671 COLUMNS, or the detected screen width if COLUMNS is not
1672 set. In addition, if columns is zero then the wrapped
1673 format only affects screen output. If columns is nonzero
1674 then file and pipe output is wrapped to that width as
1678 Specifies the field separator to be used in CSV output
1679 format. If the separator character appears in a field's
1680 value, that field is output within double quotes,
1681 following standard CSV rules. The default is a comma.
1684 If value is specified it must be either on or off, which
1685 will enable or disable expanded mode, or auto. If value is
1686 omitted the command toggles between the on and off
1687 settings. When expanded mode is enabled, query results are
1688 displayed in two columns, with the column name on the left
1689 and the data on the right. This mode is useful if the data
1690 wouldn't fit on the screen in the normal “horizontal”
1691 mode. In the auto setting, the expanded mode is used
1692 whenever the query output has more than one column and is
1693 wider than the screen; otherwise, the regular mode is
1694 used. The auto setting is only effective in the aligned
1695 and wrapped formats. In other formats, it always behaves
1696 as if the expanded mode is off.
1699 Specifies the field separator to be used in unaligned
1700 output format. That way one can create, for example,
1701 tab-separated output, which other programs might prefer.
1702 To set a tab as field separator, type \pset fieldsep '\t'.
1703 The default field separator is '|' (a vertical bar).
1706 Sets the field separator to use in unaligned output format
1710 If value is specified it must be either on or off which
1711 will enable or disable display of the table footer (the (n
1712 rows) count). If value is omitted the command toggles
1713 footer display on or off.
1716 Sets the output format to one of aligned, asciidoc, csv,
1717 html, latex, latex-longtable, troff-ms, unaligned, or
1718 wrapped. Unique abbreviations are allowed.
1720 aligned format is the standard, human-readable, nicely
1721 formatted text output; this is the default.
1723 unaligned format writes all columns of a row on one line,
1724 separated by the currently active field separator. This is
1725 useful for creating output that might be intended to be
1726 read in by other programs, for example, tab-separated or
1727 comma-separated format. However, the field separator
1728 character is not treated specially if it appears in a
1729 column's value; so CSV format may be better suited for
1732 csv format writes column values separated by commas,
1733 applying the quoting rules described in RFC 4180. This
1734 output is compatible with the CSV format of the server's
1735 COPY command. A header line with column names is generated
1736 unless the tuples_only parameter is on. Titles and footers
1737 are not printed. Each row is terminated by the
1738 system-dependent end-of-line character, which is typically
1739 a single newline (\n) for Unix-like systems or a carriage
1740 return and newline sequence (\r\n) for Microsoft Windows.
1741 Field separator characters other than comma can be
1742 selected with \pset csv_fieldsep.
1744 wrapped format is like aligned but wraps wide data values
1745 across lines to make the output fit in the target column
1746 width. The target width is determined as described under
1747 the columns option. Note that psql will not attempt to
1748 wrap column header titles; therefore, wrapped format
1749 behaves the same as aligned if the total width needed for
1750 column headers exceeds the target.
1752 The asciidoc, html, latex, latex-longtable, and troff-ms
1753 formats put out tables that are intended to be included in
1754 documents using the respective mark-up language. They are
1755 not complete documents! This might not be necessary in
1756 HTML, but in LaTeX you must have a complete document
1757 wrapper. The latex format uses LaTeX's tabular
1758 environment. The latex-longtable format requires the LaTeX
1759 longtable and booktabs packages.
1762 Sets the border line drawing style to one of ascii,
1763 old-ascii, or unicode. Unique abbreviations are allowed.
1764 (That would mean one letter is enough.) The default
1765 setting is ascii. This option only affects the aligned and
1766 wrapped output formats.
1768 ascii style uses plain ASCII characters. Newlines in data
1769 are shown using a + symbol in the right-hand margin. When
1770 the wrapped format wraps data from one line to the next
1771 without a newline character, a dot (.) is shown in the
1772 right-hand margin of the first line, and again in the
1773 left-hand margin of the following line.
1775 old-ascii style uses plain ASCII characters, using the
1776 formatting style used in PostgreSQL 8.4 and earlier.
1777 Newlines in data are shown using a : symbol in place of
1778 the left-hand column separator. When the data is wrapped
1779 from one line to the next without a newline character, a ;
1780 symbol is used in place of the left-hand column separator.
1782 unicode style uses Unicode box-drawing characters.
1783 Newlines in data are shown using a carriage return symbol
1784 in the right-hand margin. When the data is wrapped from
1785 one line to the next without a newline character, an
1786 ellipsis symbol is shown in the right-hand margin of the
1787 first line, and again in the left-hand margin of the
1790 When the border setting is greater than zero, the
1791 linestyle option also determines the characters with which
1792 the border lines are drawn. Plain ASCII characters work
1793 everywhere, but Unicode characters look nicer on displays
1794 that recognize them.
1797 Sets the string to be printed in place of a null value.
1798 The default is to print nothing, which can easily be
1799 mistaken for an empty string. For example, one might
1800 prefer \pset null '(null)'.
1803 If value is specified it must be either on or off which
1804 will enable or disable display of a locale-specific
1805 character to separate groups of digits to the left of the
1806 decimal marker. If value is omitted the command toggles
1807 between regular and locale-specific numeric output.
1810 Controls use of a pager program for query and psql help
1811 output. When the pager option is off, the pager program is
1812 not used. When the pager option is on, the pager is used
1813 when appropriate, i.e., when the output is to a terminal
1814 and will not fit on the screen. The pager option can also
1815 be set to always, which causes the pager to be used for
1816 all terminal output regardless of whether it fits on the
1817 screen. \pset pager without a value toggles pager use on
1820 If the environment variable PSQL_PAGER or PAGER is set,
1821 output to be paged is piped to the specified program.
1822 Otherwise a platform-dependent default program (such as
1825 When using the \watch command to execute a query
1826 repeatedly, the environment variable PSQL_WATCH_PAGER is
1827 used to find the pager program instead, on Unix systems.
1828 This is configured separately because it may confuse
1829 traditional pagers, but can be used to send output to
1830 tools that understand psql's output format (such as pspg
1834 If pager_min_lines is set to a number greater than the
1835 page height, the pager program will not be called unless
1836 there are at least this many lines of output to show. The
1837 default setting is 0.
1840 Specifies the record (line) separator to use in unaligned
1841 output format. The default is a newline character.
1844 Sets the record separator to use in unaligned output
1845 format to a zero byte.
1848 In HTML format, this specifies attributes to be placed
1849 inside the table tag. This could for example be
1850 cellpadding or bgcolor. Note that you probably don't want
1851 to specify border here, as that is already taken care of
1852 by \pset border. If no value is given, the table
1853 attributes are unset.
1855 In latex-longtable format, this controls the proportional
1856 width of each column containing a left-aligned data type.
1857 It is specified as a whitespace-separated list of values,
1858 e.g., '0.2 0.2 0.6'. Unspecified output columns use the
1859 last specified value.
1862 Sets the table title for any subsequently printed tables.
1863 This can be used to give your output descriptive tags. If
1864 no value is given, the title is unset.
1866 tuples_only (or t) #
1867 If value is specified it must be either on or off which
1868 will enable or disable tuples-only mode. If value is
1869 omitted the command toggles between regular and
1870 tuples-only output. Regular output includes extra
1871 information such as column headers, titles, and various
1872 footers. In tuples-only mode, only actual table data is
1875 unicode_border_linestyle #
1876 Sets the border drawing style for the unicode line style
1877 to one of single or double.
1879 unicode_column_linestyle #
1880 Sets the column drawing style for the unicode line style
1881 to one of single or double.
1883 unicode_header_linestyle #
1884 Sets the header drawing style for the unicode line style
1885 to one of single or double.
1888 Sets the maximum width of the header for expanded output
1889 to one of full (the default value), column, page, or an
1892 full: the expanded header is not truncated, and will be as
1893 wide as the widest output line.
1895 column: truncate the header line to the width of the first
1898 page: truncate the header line to the terminal width.
1900 integer value: specify the exact maximum width of the
1903 Illustrations of how these different formats look can be seen in
1908 There are various shortcut commands for \pset. See \a, \C, \f,
1912 Quits the psql program. In a script file, only execution of that
1913 script is terminated.
1915 \qecho text [ ... ] #
1916 This command is identical to \echo except that the output will
1917 be written to the query output channel, as set by \o.
1920 Resets (clears) the query buffer.
1922 \restrict restrict_key #
1923 Enter "restricted" mode with the provided key. In this mode, the
1924 only allowed meta-command is \unrestrict, to exit restricted
1925 mode. The key may contain only alphanumeric characters.
1927 This command is primarily intended for use in plain-text dumps
1928 generated by pg_dump, pg_dumpall, and pg_restore, but it may be
1932 Print psql's command line history to filename. If filename is
1933 omitted, the history is written to the standard output (using
1934 the pager if appropriate). This command is not available if psql
1935 was built without Readline support.
1937 \set [ name [ value [ ... ] ] ] #
1938 Sets the psql variable name to value, or if more than one value
1939 is given, to the concatenation of all of them. If only one
1940 argument is given, the variable is set to an empty-string value.
1941 To unset a variable, use the \unset command.
1943 \set without any arguments displays the names and values of all
1944 currently-set psql variables.
1946 Valid variable names can contain letters, digits, and
1947 underscores. See Variables below for details. Variable names are
1950 Certain variables are special, in that they control psql's
1951 behavior or are automatically set to reflect connection state.
1952 These variables are documented in Variables, below.
1956 This command is unrelated to the SQL command SET.
1958 \setenv name [ value ] #
1959 Sets the environment variable name to value, or if the value is
1960 not supplied, unsets the environment variable. Example:
1962 testdb=> \setenv PAGER less
1963 testdb=> \setenv LESS -imx4F
1965 \sf[+] function_description #
1966 This command fetches and shows the definition of the named
1967 function or procedure, in the form of a CREATE OR REPLACE
1968 FUNCTION or CREATE OR REPLACE PROCEDURE command. The definition
1969 is printed to the current query output channel, as set by \o.
1971 The target function can be specified by name alone, or by name
1972 and arguments, for example foo(integer, text). The argument
1973 types must be given if there is more than one function of the
1976 If + is appended to the command name, then the output lines are
1977 numbered, with the first line of the function body being line 1.
1979 Unlike most other meta-commands, the entire remainder of the
1980 line is always taken to be the argument(s) of \sf, and neither
1981 variable interpolation nor backquote expansion are performed in
1985 This command fetches and shows the definition of the named view,
1986 in the form of a CREATE OR REPLACE VIEW command. The definition
1987 is printed to the current query output channel, as set by \o.
1989 If + is appended to the command name, then the output lines are
1992 Unlike most other meta-commands, the entire remainder of the
1993 line is always taken to be the argument(s) of \sv, and neither
1994 variable interpolation nor backquote expansion are performed in
2003 \getresults [ number_results ] #
2004 This group of commands implements pipelining of SQL statements.
2005 A pipeline must begin with a \startpipeline and end with an
2006 \endpipeline. In between there may be any number of
2007 \syncpipeline commands, which sends a sync message without
2008 ending the ongoing pipeline and flushing the send buffer. In
2009 pipeline mode, statements are sent to the server without waiting
2010 for the results of previous statements. See Section 32.5 for
2013 All queries executed while a pipeline is ongoing use the
2014 extended query protocol. Queries are appended to the pipeline
2015 when ending with a semicolon. The meta-commands \bind,
2016 \bind_named, \close_prepared or \parse can be used in an ongoing
2017 pipeline. While a pipeline is ongoing, \sendpipeline will append
2018 the current query buffer to the pipeline. Other meta-commands
2019 like \g, \gx or \gdesc are not allowed in pipeline mode.
2021 \flushrequest appends a flush command to the pipeline, allowing
2022 to read results with \getresults without issuing a sync or
2023 ending the pipeline. \getresults will automatically push unsent
2024 data to the server. \flush can be used to manually push unsent
2027 \getresults accepts an optional number_results parameter. If
2028 provided, only the first number_results pending results will be
2029 read. If not provided or 0, all pending results are read.
2031 When pipeline mode is active, a dedicated prompt variable is
2032 available to report the pipeline status. See %P for more details
2034 COPY is not supported while in pipeline mode.
2039 SELECT * FROM pg_class;
2040 SELECT 1 \bind \sendpipeline
2046 Toggles the display of output column name headings and row count
2047 footer. This command is equivalent to \pset tuples_only and is
2048 provided for convenience.
2051 Specifies attributes to be placed within the table tag in HTML
2052 output format. This command is equivalent to \pset tableattr
2055 \timing [ on | off ] #
2056 With a parameter, turns displaying of how long each SQL
2057 statement takes on or off. Without a parameter, toggles the
2058 display between on and off. The display is in milliseconds;
2059 intervals longer than 1 second are also shown in minutes:seconds
2060 format, with hours and days fields added if needed.
2062 \unrestrict restrict_key #
2063 Exit "restricted" mode (i.e., where all other meta-commands are
2064 blocked), provided the specified key matches the one given to
2065 \restrict when restricted mode was entered.
2067 This command is primarily intended for use in plain-text dumps
2068 generated by pg_dump, pg_dumpall, and pg_restore, but it may be
2072 Unsets (deletes) the psql variable name.
2074 Most variables that control psql's behavior cannot be unset;
2075 instead, an \unset command is interpreted as setting them to
2076 their default values. See Variables below.
2078 \w or \write filename
2079 \w or \write |command #
2080 Writes the current query buffer to the file filename or pipes it
2081 to the shell command command. If the current query buffer is
2082 empty, the most recently executed query is written instead.
2084 If the argument begins with |, then the entire remainder of the
2085 line is taken to be the command to execute, and neither variable
2086 interpolation nor backquote expansion are performed in it. The
2087 rest of the line is simply passed literally to the shell.
2089 \warn text [ ... ] #
2090 This command is identical to \echo except that the output will
2091 be written to psql's standard error channel, rather than
2094 \watch [ i[nterval]=seconds ] [ c[ount]=times ] [ m[in_rows]=rows ] [
2096 Repeatedly execute the current query buffer (as \g does) until
2097 interrupted, or the query fails, or the execution count limit
2098 (if given) is reached, or the query no longer returns the
2099 minimum number of rows. Wait the specified number of seconds
2100 (default 2) between executions. The default wait can be changed
2101 with the variable WATCH_INTERVAL. For backwards compatibility,
2102 seconds can be specified with or without an interval= prefix.
2103 Each query result is displayed with a header that includes the
2104 \pset title string (if any), the time as of query start, and the
2107 If the current query buffer is empty, the most recently sent
2108 query is re-executed instead.
2110 \x [ on | off | auto ] #
2111 Sets or toggles expanded table formatting mode. As such it is
2112 equivalent to \pset expanded.
2114 \z[Sx] [ pattern ] #
2115 Lists tables, views and sequences with their associated access
2116 privileges. If a pattern is specified, only tables, views and
2117 sequences whose names match the pattern are listed. By default
2118 only user-created objects are shown; supply a pattern or the S
2119 modifier to include system objects. If x is appended to the
2120 command name, the results are displayed in expanded mode.
2122 This is an alias for \dp (“display privileges”).
2125 With no argument, escapes to a sub-shell; psql resumes when the
2126 sub-shell exits. With an argument, executes the shell command
2129 Unlike most other meta-commands, the entire remainder of the
2130 line is always taken to be the argument(s) of \!, and neither
2131 variable interpolation nor backquote expansion are performed in
2132 the arguments. The rest of the line is simply passed literally
2136 Shows help information. The optional topic parameter (defaulting
2137 to commands) selects which part of psql is explained: commands
2138 describes psql's backslash commands; options describes the
2139 command-line options that can be passed to psql; and variables
2140 shows help about psql configuration variables.
2143 Backslash-semicolon is not a meta-command in the same way as the
2144 preceding commands; rather, it simply causes a semicolon to be
2145 added to the query buffer without any further processing.
2147 Normally, psql will dispatch an SQL command to the server as
2148 soon as it reaches the command-ending semicolon, even if more
2149 input remains on the current line. Thus for example entering
2151 select 1; select 2; select 3;
2153 will result in the three SQL commands being individually sent to
2154 the server, with each one's results being displayed before
2155 continuing to the next command. However, a semicolon entered as
2156 \; will not trigger command processing, so that the command
2157 before it and the one after are effectively combined and sent to
2158 the server in one request. So for example
2160 select 1\; select 2\; select 3;
2162 results in sending the three SQL commands to the server in a
2163 single request, when the non-backslashed semicolon is reached.
2164 The server executes such a request as a single transaction,
2165 unless there are explicit BEGIN/COMMIT commands included in the
2166 string to divide it into multiple transactions. (See
2167 Section 54.2.2.1 for more details about how the server handles
2168 multi-query strings.)
2172 The various \d commands accept a pattern parameter to specify the
2173 object name(s) to be displayed. In the simplest case, a pattern is just
2174 the exact name of the object. The characters within a pattern are
2175 normally folded to lower case, just as in SQL names; for example, \dt
2176 FOO will display the table named foo. As in SQL names, placing double
2177 quotes around a pattern stops folding to lower case. Should you need to
2178 include an actual double quote character in a pattern, write it as a
2179 pair of double quotes within a double-quote sequence; again this is in
2180 accord with the rules for SQL quoted identifiers. For example, \dt
2181 "FOO""BAR" will display the table named FOO"BAR (not foo"bar). Unlike
2182 the normal rules for SQL names, you can put double quotes around just
2183 part of a pattern, for instance \dt FOO"FOO"BAR will display the table
2186 Whenever the pattern parameter is omitted completely, the \d commands
2187 display all objects that are visible in the current schema search path
2188 — this is equivalent to using * as the pattern. (An object is said to
2189 be visible if its containing schema is in the search path and no object
2190 of the same kind and name appears earlier in the search path. This is
2191 equivalent to the statement that the object can be referenced by name
2192 without explicit schema qualification.) To see all objects in the
2193 database regardless of visibility, use *.* as the pattern.
2195 Within a pattern, * matches any sequence of characters (including no
2196 characters) and ? matches any single character. (This notation is
2197 comparable to Unix shell file name patterns.) For example, \dt int*
2198 displays tables whose names begin with int. But within double quotes, *
2199 and ? lose these special meanings and are just matched literally.
2201 A relation pattern that contains a dot (.) is interpreted as a schema
2202 name pattern followed by an object name pattern. For example, \dt
2203 foo*.*bar* displays all tables whose table name includes bar that are
2204 in schemas whose schema name starts with foo. When no dot appears, then
2205 the pattern matches only objects that are visible in the current schema
2206 search path. Again, a dot within double quotes loses its special
2207 meaning and is matched literally. A relation pattern that contains two
2208 dots (.) is interpreted as a database name followed by a schema name
2209 pattern followed by an object name pattern. The database name portion
2210 will not be treated as a pattern and must match the name of the
2211 currently connected database, else an error will be raised.
2213 A schema pattern that contains a dot (.) is interpreted as a database
2214 name followed by a schema name pattern. For example, \dn mydb.*foo*
2215 displays all schemas whose schema name includes foo. The database name
2216 portion will not be treated as a pattern and must match the name of the
2217 currently connected database, else an error will be raised.
2219 Advanced users can use regular-expression notations such as character
2220 classes, for example [0-9] to match any digit. All regular expression
2221 special characters work as specified in Section 9.7.3, except for .
2222 which is taken as a separator as mentioned above, * which is translated
2223 to the regular-expression notation .*, ? which is translated to ., and
2224 $ which is matched literally. You can emulate these pattern characters
2225 at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not
2226 needed as a regular-expression character since the pattern must match
2227 the whole name, unlike the usual interpretation of regular expressions
2228 (in other words, $ is automatically appended to your pattern). Write *
2229 at the beginning and/or end if you don't wish the pattern to be
2230 anchored. Note that within double quotes, all regular expression
2231 special characters lose their special meanings and are matched
2232 literally. Also, the regular expression special characters are matched
2233 literally in operator name patterns (i.e., the argument of \do).
2239 psql provides variable substitution features similar to common Unix
2240 command shells. Variables are simply name/value pairs, where the value
2241 can be any string of any length. The name must consist of letters
2242 (including non-Latin letters), digits, and underscores.
2244 To set a variable, use the psql meta-command \set. For example,
2245 testdb=> \set foo bar
2247 sets the variable foo to the value bar. To retrieve the content of the
2248 variable, precede the name with a colon, for example:
2252 This works in both regular SQL commands and meta-commands; there is
2253 more detail in SQL Interpolation, below.
2255 If you call \set without a second argument, the variable is set to an
2256 empty-string value. To unset (i.e., delete) a variable, use the command
2257 \unset. To show the values of all variables, call \set without any
2262 The arguments of \set are subject to the same substitution rules as
2263 with other commands. Thus you can construct interesting references such
2264 as \set :foo 'something' and get “soft links” or “variable variables”
2265 of Perl or PHP fame, respectively. Unfortunately (or fortunately?),
2266 there is no way to do anything useful with these constructs. On the
2267 other hand, \set bar :foo is a perfectly valid way to copy a variable.
2269 A number of these variables are treated specially by psql. They
2270 represent certain option settings that can be changed at run time by
2271 altering the value of the variable, or in some cases represent
2272 changeable state of psql. By convention, all specially treated
2273 variables' names consist of all upper-case ASCII letters (and possibly
2274 digits and underscores). To ensure maximum compatibility in the future,
2275 avoid using such variable names for your own purposes.
2277 Variables that control psql's behavior generally cannot be unset or set
2278 to invalid values. An \unset command is allowed but is interpreted as
2279 setting the variable to its default value. A \set command without a
2280 second argument is interpreted as setting the variable to on, for
2281 control variables that accept that value, and is rejected for others.
2282 Also, control variables that accept the values on and off will also
2283 accept other common spellings of Boolean values, such as true and
2286 The specially treated variables are:
2289 When on (the default), each SQL command is automatically
2290 committed upon successful completion. To postpone commit in this
2291 mode, you must enter a BEGIN or START TRANSACTION SQL command.
2292 When off or unset, SQL commands are not committed until you
2293 explicitly issue COMMIT or END. The autocommit-off mode works by
2294 issuing an implicit BEGIN for you, just before any command that
2295 is not already in a transaction block and is not itself a BEGIN
2296 or other transaction-control command, nor a command that cannot
2297 be executed inside a transaction block (such as VACUUM).
2301 In autocommit-off mode, you must explicitly abandon any failed
2302 transaction by entering ABORT or ROLLBACK. Also keep in mind
2303 that if you exit the session without committing, your work will
2308 The autocommit-on mode is PostgreSQL's traditional behavior, but
2309 autocommit-off is closer to the SQL spec. If you prefer
2310 autocommit-off, you might wish to set it in the system-wide
2311 psqlrc file or your ~/.psqlrc file.
2314 Determines which letter case to use when completing an SQL key
2315 word. If set to lower or upper, the completed word will be in
2316 lower or upper case, respectively. If set to preserve-lower or
2317 preserve-upper (the default), the completed word will be in the
2318 case of the word already entered, but words being completed
2319 without anything entered will be in lower or upper case,
2323 The name of the database you are currently connected to. This is
2324 set every time you connect to a database (including program
2325 start-up), but can be changed or unset.
2328 If set to all, all nonempty input lines are printed to standard
2329 output as they are read. (This does not apply to lines read
2330 interactively.) To select this behavior on program start-up, use
2331 the switch -a. If set to queries, psql prints each query to
2332 standard output as it is sent to the server. The switch to
2333 select this behavior is -e. If set to errors, then only failed
2334 queries are displayed on standard error output. The switch for
2335 this behavior is -b. If set to none (the default), then no
2336 queries are displayed.
2339 When this variable is set to on and a backslash command queries
2340 the database, the query is first shown. This feature helps you
2341 to study PostgreSQL internals and provide similar functionality
2342 in your own programs. (To select this behavior on program
2343 start-up, use the switch -E.) If you set this variable to the
2344 value noexec, the queries are just shown but are not actually
2345 sent to the server and executed. The default value is off.
2348 The current client character set encoding. This is set every
2349 time you connect to a database (including program start-up), and
2350 when you change the encoding with \encoding, but it can be
2354 true if the last SQL query failed, false if it succeeded. See
2358 If this variable is set to an integer value greater than zero,
2359 the results of SELECT queries are fetched and displayed in
2360 groups of that many rows, rather than the default behavior of
2361 collecting the entire result set before display. Therefore only
2362 a limited amount of memory is used, regardless of the size of
2363 the result set. Settings of 100 to 1000 are commonly used when
2364 enabling this feature. Keep in mind that when using this
2365 feature, a query might fail after having already displayed some
2370 Although you can use any output format with this feature, the
2371 default aligned format tends to look bad because each group of
2372 FETCH_COUNT rows will be formatted separately, leading to
2373 varying column widths across the row groups. The other output
2374 formats work better.
2377 If this variable is set to true, a table's access method details
2378 are not displayed. This is mainly useful for regression tests.
2380 HIDE_TOAST_COMPRESSION #
2381 If this variable is set to true, column compression method
2382 details are not displayed. This is mainly useful for regression
2386 If this variable is set to ignorespace, lines which begin with a
2387 space are not entered into the history list. If set to a value
2388 of ignoredups, lines matching the previous history line are not
2389 entered. A value of ignoreboth combines the two options. If set
2390 to none (the default), all lines read in interactive mode are
2391 saved on the history list.
2395 This feature was shamelessly plagiarized from Bash.
2398 The file name that will be used to store the history list. If
2399 unset, the file name is taken from the PSQL_HISTORY environment
2400 variable. If that is not set either, the default is
2401 ~/.psql_history, or %APPDATA%\postgresql\psql_history on
2402 Windows. For example, putting:
2404 \set HISTFILE ~/.psql_history-:DBNAME
2406 in ~/.psqlrc will cause psql to maintain a separate history for
2411 This feature was shamelessly plagiarized from Bash.
2414 The maximum number of commands to store in the command history
2415 (default 500). If set to a negative value, no limit is applied.
2419 This feature was shamelessly plagiarized from Bash.
2422 The database server host you are currently connected to. This is
2423 set every time you connect to a database (including program
2424 start-up), but can be changed or unset.
2427 If set to 1 or less, sending an EOF character (usually
2428 Control+D) to an interactive session of psql will terminate the
2429 application. If set to a larger numeric value, that many
2430 consecutive EOF characters must be typed to make an interactive
2431 session terminate. If the variable is set to a non-numeric
2432 value, it is interpreted as 10. The default is 0.
2436 This feature was shamelessly plagiarized from Bash.
2439 The value of the last affected OID, as returned from an INSERT
2440 or \lo_import command. This variable is only guaranteed to be
2441 valid until after the result of the next SQL command has been
2442 displayed. PostgreSQL servers since version 12 do not support
2443 OID system columns anymore, thus LASTOID will always be 0
2444 following INSERT when targeting such servers.
2447 LAST_ERROR_SQLSTATE #
2448 The primary error message and associated SQLSTATE code for the
2449 most recent failed query in the current psql session, or an
2450 empty string and 00000 if no error has occurred in the current
2454 When set to on, if a statement in a transaction block generates
2455 an error, the error is ignored and the transaction continues.
2456 When set to interactive, such errors are only ignored in
2457 interactive sessions, and not when reading script files. When
2458 set to off (the default), a statement in a transaction block
2459 that generates an error aborts the entire transaction. The error
2460 rollback mode works by issuing an implicit SAVEPOINT for you,
2461 just before each command that is in a transaction block, and
2462 then rolling back to the savepoint if the command fails.
2465 By default, command processing continues after an error. When
2466 this variable is set to on, processing will instead stop
2467 immediately. In interactive mode, psql will return to the
2468 command prompt; otherwise, psql will exit, returning error code
2469 3 to distinguish this case from fatal error conditions, which
2470 are reported using error code 1. In either case, any currently
2471 running scripts (the top-level script, if any, and any other
2472 scripts which it may have in invoked) will be terminated
2473 immediately. If the top-level command string contained multiple
2474 SQL commands, processing will stop with the current command.
2476 PIPELINE_COMMAND_COUNT #
2477 The number of commands queued in an ongoing pipeline.
2479 PIPELINE_RESULT_COUNT #
2480 The number of commands of an ongoing pipeline that were followed
2481 by either a \flushrequest or a \syncpipeline, forcing the server
2482 to send the results. These results can be retrieved with
2485 PIPELINE_SYNC_COUNT #
2486 The number of sync messages queued in an ongoing pipeline.
2489 The database server port to which you are currently connected.
2490 This is set every time you connect to a database (including
2491 program start-up), but can be changed or unset.
2496 These specify what the prompts psql issues should look like. See
2500 Setting this variable to on is equivalent to the command line
2501 option -q. It is probably not too useful in interactive mode.
2504 The number of rows returned or affected by the last SQL query,
2505 or 0 if the query failed or did not report a row count.
2508 SERVER_VERSION_NUM #
2509 The server's version number as a string, for example 9.6.2, 10.1
2510 or 11beta1, and in numeric form, for example 90602 or 100001.
2511 These are set every time you connect to a database (including
2512 program start-up), but can be changed or unset.
2515 The service name, if applicable.
2518 true if the last shell command failed, false if it succeeded.
2519 This applies to shell commands invoked via the \!, \g, \o, \w,
2520 and \copy meta-commands, as well as backquote (`) expansion.
2521 Note that for \o, this variable is updated when the output pipe
2522 is closed by the next \o command. See also SHELL_EXIT_CODE.
2525 The exit status returned by the last shell command. 0–127
2526 represent program exit codes, 128–255 indicate termination by a
2527 signal, and -1 indicates failure to launch a program or to
2528 collect its exit status. This applies to shell commands invoked
2529 via the \!, \g, \o, \w, and \copy meta-commands, as well as
2530 backquote (`) expansion. Note that for \o, this variable is
2531 updated when the output pipe is closed by the next \o command.
2532 See also SHELL_ERROR.
2535 When this variable is set to off, only the last result of a
2536 combined query (\;) is shown instead of all of them. The default
2537 is on. The off behavior is for compatibility with older versions
2541 This variable can be set to the values never, errors, or always
2542 to control whether CONTEXT fields are displayed in messages from
2543 the server. The default is errors (meaning that context will be
2544 shown in error messages, but not in notice or warning messages).
2545 This setting has no effect when VERBOSITY is set to terse or
2546 sqlstate. (See also \errverbose, for use when you want a verbose
2547 version of the error you just got.)
2550 Setting this variable to on is equivalent to the command line
2554 Setting this variable to on is equivalent to the command line
2558 The error code (see Appendix A) associated with the last SQL
2559 query's failure, or 00000 if it succeeded.
2562 The database user you are currently connected as. This is set
2563 every time you connect to a database (including program
2564 start-up), but can be changed or unset.
2567 This variable can be set to the values default, verbose, terse,
2568 or sqlstate to control the verbosity of error reports. (See also
2569 \errverbose, for use when you want a verbose version of the
2570 error you just got.)
2575 These variables are set at program start-up to reflect psql's
2576 version, respectively as a verbose string, a short string (e.g.,
2577 9.6.2, 10.1, or 11beta1), and a number (e.g., 90602 or 100001).
2578 They can be changed or unset.
2581 This variable sets the default interval, in seconds, which
2582 \watch waits between executing the query. The default is 2
2583 seconds. Specifying an interval in the command overrides this
2588 A key feature of psql variables is that you can substitute
2589 (“interpolate”) them into regular SQL statements, as well as the
2590 arguments of meta-commands. Furthermore, psql provides facilities for
2591 ensuring that variable values used as SQL literals and identifiers are
2592 properly quoted. The syntax for interpolating a value without any
2593 quoting is to prepend the variable name with a colon (:). For example,
2594 testdb=> \set foo 'my_table'
2595 testdb=> SELECT * FROM :foo;
2597 would query the table my_table. Note that this may be unsafe: the value
2598 of the variable is copied literally, so it can contain unbalanced
2599 quotes, or even backslash commands. You must make sure that it makes
2600 sense where you put it.
2602 When a value is to be used as an SQL literal or identifier, it is
2603 safest to arrange for it to be quoted. To quote the value of a variable
2604 as an SQL literal, write a colon followed by the variable name in
2605 single quotes. To quote the value as an SQL identifier, write a colon
2606 followed by the variable name in double quotes. These constructs deal
2607 correctly with quotes and other special characters embedded within the
2608 variable value. The previous example would be more safely written this
2610 testdb=> \set foo 'my_table'
2611 testdb=> SELECT * FROM :"foo";
2613 Variable interpolation will not be performed within quoted SQL literals
2614 and identifiers. Therefore, a construction such as ':foo' doesn't work
2615 to produce a quoted literal from a variable's value (and it would be
2616 unsafe if it did work, since it wouldn't correctly handle quotes
2617 embedded in the value).
2619 One example use of this mechanism is to copy the contents of a file
2620 into a table column. First load the file into a variable and then
2621 interpolate the variable's value as a quoted string:
2622 testdb=> \set content `cat my_file.txt`
2623 testdb=> INSERT INTO my_table VALUES (:'content');
2625 (Note that this still won't work if my_file.txt contains NUL bytes.
2626 psql does not support embedded NUL bytes in variable values.)
2628 Since colons can legally appear in SQL commands, an apparent attempt at
2629 interpolation (that is, :name, :'name', or :"name") is not replaced
2630 unless the named variable is currently set. In any case, you can escape
2631 a colon with a backslash to protect it from substitution.
2633 The :{?name} special syntax returns TRUE or FALSE depending on whether
2634 the variable exists or not, and is thus always substituted, unless the
2635 colon is backslash-escaped.
2637 The colon syntax for variables is standard SQL for embedded query
2638 languages, such as ECPG. The colon syntaxes for array slices and type
2639 casts are PostgreSQL extensions, which can sometimes conflict with the
2640 standard usage. The colon-quote syntax for escaping a variable's value
2641 as an SQL literal or identifier is a psql extension.
2645 The prompts psql issues can be customized to your preference. The three
2646 variables PROMPT1, PROMPT2, and PROMPT3 contain strings and special
2647 escape sequences that describe the appearance of the prompt. Prompt 1
2648 is the normal prompt that is issued when psql requests a new command.
2649 Prompt 2 is issued when more input is expected during command entry,
2650 for example because the command was not terminated with a semicolon or
2651 a quote was not closed. Prompt 3 is issued when you are running an SQL
2652 COPY FROM STDIN command and you need to type in a row value on the
2655 The value of the selected prompt variable is printed literally, except
2656 where a percent sign (%) is encountered. Depending on the next
2657 character, certain other text is substituted instead. Defined
2661 The full host name (with domain name) of the database server, or
2662 [local] if the connection is over a Unix domain socket, or
2663 [local:/dir/name], if the Unix domain socket is not at the
2664 compiled in default location.
2667 The host name of the database server, truncated at the first
2668 dot, or [local] if the connection is over a Unix domain socket.
2671 The port number at which the database server is listening.
2674 The database session user name. (The expansion of this value
2675 might change during a database session as the result of the
2676 command SET SESSION AUTHORIZATION.)
2679 The name of the service.
2682 The name of the current database.
2685 Like %/, but the output is ~ (tilde) if the database is your
2689 If the session user is a database superuser, then a #, otherwise
2690 a >. (The expansion of this value might change during a database
2691 session as the result of the command SET SESSION AUTHORIZATION.)
2694 The process ID of the backend currently connected to.
2697 Pipeline status: off when not in a pipeline, on when in an
2698 ongoing pipeline or abort when in an aborted pipeline.
2701 In prompt 1 normally =, but @ if the session is in an inactive
2702 branch of a conditional block, or ^ if in single-line mode, or !
2703 if the session is disconnected from the database (which can
2704 happen if \connect fails). In prompt 2 %R is replaced by a
2705 character that depends on why psql expects more input: - if the
2706 command simply wasn't terminated yet, but * if there is an
2707 unfinished /* ... */ comment, a single quote if there is an
2708 unfinished quoted string, a double quote if there is an
2709 unfinished quoted identifier, a dollar sign if there is an
2710 unfinished dollar-quoted string, or ( if there is an unmatched
2711 left parenthesis. In prompt 3 %R doesn't produce anything.
2714 Transaction status: an empty string when not in a transaction
2715 block, or * when in a transaction block, or ! when in a failed
2716 transaction block, or ? when the transaction state is
2717 indeterminate (for example, because there is no connection).
2720 The line number inside the current statement, starting from 1.
2723 The character with the indicated octal code is substituted.
2726 The value of the psql variable name. See Variables, above, for
2730 The output of command, similar to ordinary “back-tick”
2734 Prompts can contain terminal control characters which, for
2735 example, change the color, background, or style of the prompt
2736 text, or change the title of the terminal window. In order for
2737 the line editing features of Readline to work properly, these
2738 non-printing control characters must be designated as invisible
2739 by surrounding them with %[ and %]. Multiple pairs of these can
2740 occur within the prompt. For example:
2742 testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# '
2744 results in a boldfaced (1;) yellow-on-black (33;40) prompt on
2745 VT100-compatible, color-capable terminals.
2748 Whitespace of the same width as the most recent output of
2749 PROMPT1. This can be used as a PROMPT2 setting, so that
2750 multi-line statements are aligned with the first line, but there
2751 is no visible secondary prompt.
2753 To insert a percent sign into your prompt, write %%. The default
2754 prompts are '%/%R%x%# ' for prompts 1 and 2, and '>> ' for prompt 3.
2758 This feature was shamelessly plagiarized from tcsh.
2760 Command-Line Editing
2762 psql uses the Readline or libedit library, if available, for convenient
2763 line editing and retrieval. The command history is automatically saved
2764 when psql exits and is reloaded when psql starts up. Type up-arrow or
2765 control-P to retrieve previous lines.
2767 You can also use tab completion to fill in partially-typed keywords and
2768 SQL object names in many (by no means all) contexts. For example, at
2769 the start of a command, typing ins and pressing TAB will fill in insert
2770 into . Then, typing a few characters of a table or schema name and
2771 pressing TAB will fill in the unfinished name, or offer a menu of
2772 possible completions when there's more than one. (Depending on the
2773 library in use, you may need to press TAB more than once to get a
2776 Tab completion for SQL object names requires sending queries to the
2777 server to find possible matches. In some contexts this can interfere
2778 with other operations. For example, after BEGIN it will be too late to
2779 issue SET TRANSACTION ISOLATION LEVEL if a tab-completion query is
2780 issued in between. If you do not want tab completion at all, you can
2781 turn it off permanently by putting this in a file named .inputrc in
2782 your home directory:
2784 set disable-completion on
2787 (This is not a psql but a Readline feature. Read its documentation for
2790 The -n (--no-readline) command line option can also be useful to
2791 disable use of Readline for a single run of psql. This prevents tab
2792 completion, use or recording of command line history, and editing of
2793 multi-line commands. It is particularly useful when you need to
2794 copy-and-paste text that contains TAB characters.
2799 If \pset columns is zero, controls the width for the wrapped
2800 format and width for determining if wide output requires the
2801 pager or should be switched to the vertical format in expanded
2808 Default connection parameters (see Section 32.15).
2811 Specifies whether to use color in diagnostic messages. Possible
2812 values are always, auto and never.
2817 Editor used by the \e, \ef, and \ev commands. These variables
2818 are examined in the order listed; the first that is set is used.
2819 If none of them is set, the default is to use vi on Unix systems
2820 or notepad.exe on Windows systems.
2822 PSQL_EDITOR_LINENUMBER_ARG #
2823 When \e, \ef, or \ev is used with a line number argument, this
2824 variable specifies the command-line argument used to pass the
2825 starting line number to the user's editor. For editors such as
2826 Emacs or vi, this is a plus sign. Include a trailing space in
2827 the value of the variable if there needs to be space between the
2828 option name and the line number. Examples:
2830 PSQL_EDITOR_LINENUMBER_ARG='+'
2831 PSQL_EDITOR_LINENUMBER_ARG='--line '
2833 The default is + on Unix systems (corresponding to the default
2834 editor vi, and useful for many other common editors); but there
2835 is no default on Windows systems.
2838 Alternative location for the command history file. Tilde (~)
2839 expansion is performed.
2843 If a query's results do not fit on the screen, they are piped
2844 through this command. Typical values are more or less. Use of
2845 the pager can be disabled by setting PSQL_PAGER or PAGER to an
2846 empty string, or by adjusting the pager-related options of the
2847 \pset command. These variables are examined in the order listed;
2848 the first that is set is used. If neither of them is set, the
2849 default is to use more on most platforms, but less on Cygwin.
2852 When a query is executed repeatedly with the \watch command, a
2853 pager is not used by default. This behavior can be changed by
2854 setting PSQL_WATCH_PAGER to a pager command, on Unix systems.
2855 The pspg pager (not part of PostgreSQL but available in many
2856 open source software distributions) can display the output of
2857 \watch if started with the option --stream.
2860 Alternative location of the user's .psqlrc file. Tilde (~)
2861 expansion is performed.
2864 Command executed by the \! command.
2867 Directory for storing temporary files. The default is /tmp.
2869 This utility, like most other PostgreSQL utilities, also uses the
2870 environment variables supported by libpq (see Section 32.15).
2874 psqlrc and ~/.psqlrc #
2875 Unless it is passed an -X option, psql attempts to read and
2876 execute commands from the system-wide startup file (psqlrc) and
2877 then the user's personal startup file (~/.psqlrc), after
2878 connecting to the database but before accepting normal commands.
2879 These files can be used to set up the client and/or the server
2880 to taste, typically with \set and SET commands.
2882 The system-wide startup file is named psqlrc. By default it is
2883 sought in the installation's “system configuration” directory,
2884 which is most reliably identified by running pg_config
2885 --sysconfdir. Typically this directory will be ../etc/ relative
2886 to the directory containing the PostgreSQL executables. The
2887 directory to look in can be set explicitly via the PGSYSCONFDIR
2888 environment variable.
2890 The user's personal startup file is named .psqlrc and is sought
2891 in the invoking user's home directory. On Windows the personal
2892 startup file is instead named %APPDATA%\postgresql\psqlrc.conf.
2893 In either case, this default file path can be overridden by
2894 setting the PSQLRC environment variable.
2896 Both the system-wide startup file and the user's personal
2897 startup file can be made psql-version-specific by appending a
2898 dash and the PostgreSQL major or minor release identifier to the
2899 file name, for example ~/.psqlrc-18 or ~/.psqlrc-18.0. The most
2900 specific version-matching file will be read in preference to a
2901 non-version-specific file. These version suffixes are added
2902 after determining the file path as explained above.
2905 The command-line history is stored in the file ~/.psql_history,
2906 or %APPDATA%\postgresql\psql_history on Windows.
2908 The location of the history file can be set explicitly via the
2909 HISTFILE psql variable or the PSQL_HISTORY environment variable.
2913 * psql works best with servers of the same or an older major version.
2914 Backslash commands are particularly likely to fail if the server is
2915 of a newer version than psql itself. However, backslash commands of
2916 the \d family should work with servers of versions back to 9.2,
2917 though not necessarily with servers newer than psql itself. The
2918 general functionality of running SQL commands and displaying query
2919 results should also work with servers of a newer major version, but
2920 this cannot be guaranteed in all cases.
2921 If you want to use psql to connect to several servers of different
2922 major versions, it is recommended that you use the newest version
2923 of psql. Alternatively, you can keep around a copy of psql from
2924 each major version and be sure to use the version that matches the
2925 respective server. But in practice, this additional complication
2926 should not be necessary.
2927 * Before PostgreSQL 9.6, the -c option implied -X (--no-psqlrc); this
2928 is no longer the case.
2929 * Before PostgreSQL 8.4, psql allowed the first argument of a
2930 single-letter backslash command to start directly after the
2931 command, without intervening whitespace. Now, some whitespace is
2934 Notes for Windows Users
2936 psql is built as a “console application”. Since the Windows console
2937 windows use a different encoding than the rest of the system, you must
2938 take special care when using 8-bit characters within psql. If psql
2939 detects a problematic console code page, it will warn you at startup.
2940 To change the console code page, two things are necessary:
2941 * Set the code page by entering cmd.exe /c chcp 1252. (1252 is a code
2942 page that is appropriate for German; replace it with your value.)
2943 If you are using Cygwin, you can put this command in /etc/profile.
2944 * Set the console font to Lucida Console, because the raster font
2945 does not work with the ANSI code page.
2949 The first example shows how to spread a command over several lines of
2950 input. Notice the changing prompt:
2951 testdb=> CREATE TABLE my_table (
2952 testdb(> first integer not null default 0,
2953 testdb(> second text)
2957 Now look at the table definition again:
2958 testdb=> \d my_table
2959 Table "public.my_table"
2960 Column | Type | Collation | Nullable | Default
2961 --------+---------+-----------+----------+---------
2962 first | integer | | not null | 0
2965 Now we change the prompt to something more interesting:
2966 testdb=> \set PROMPT1 '%n@%m %~%R%# '
2967 peter@localhost testdb=>
2969 Let's assume you have filled the table with data and want to take a
2971 peter@localhost testdb=> SELECT * FROM my_table;
2980 You can display tables in different ways by using the \pset command:
2981 peter@localhost testdb=> \pset border 2
2983 peter@localhost testdb=> SELECT * FROM my_table;
2994 peter@localhost testdb=> \pset border 0
2996 peter@localhost testdb=> SELECT * FROM my_table;
3005 peter@localhost testdb=> \pset border 1
3007 peter@localhost testdb=> \pset format csv
3008 Output format is csv.
3009 peter@localhost testdb=> \pset tuples_only
3011 peter@localhost testdb=> SELECT second, first FROM my_table;
3016 peter@localhost testdb=> \pset format unaligned
3017 Output format is unaligned.
3018 peter@localhost testdb=> \pset fieldsep '\t'
3019 Field separator is " ".
3020 peter@localhost testdb=> SELECT second, first FROM my_table;
3026 Alternatively, use the short commands:
3027 peter@localhost testdb=> \a \t \x
3028 Output format is aligned.
3030 Expanded display is on.
3031 peter@localhost testdb=> SELECT * FROM my_table;
3045 Also, these output format options can be set for just one query by
3047 peter@localhost testdb=> SELECT * FROM my_table
3048 peter@localhost testdb-> \g (format=aligned tuples_only=off expanded=on)
3062 Here is an example of using the \df command to find only functions with
3063 names matching int*pl and whose second argument is of type bigint:
3064 testdb=> \df int*pl * bigint
3066 Schema | Name | Result data type | Argument data types | Type
3067 ------------+---------+------------------+---------------------+------
3068 pg_catalog | int28pl | bigint | smallint, bigint | func
3069 pg_catalog | int48pl | bigint | integer, bigint | func
3070 pg_catalog | int8pl | bigint | bigint, bigint | func
3073 Here, the + option is used to display additional information about one
3074 of these functions, and x is used to display the results in expanded
3076 testdb=> \df+x int*pl integer bigint
3078 -[ RECORD 1 ]-------+-----------------------------
3081 Result data type | bigint
3082 Argument data types | integer, bigint
3084 Volatility | immutable
3091 Internal name | int48pl
3092 Description | implementation of + operator
3094 When suitable, query results can be shown in a crosstab representation
3095 with the \crosstabview command:
3096 testdb=> SELECT first, second, first > 2 AS gt2 FROM my_table;
3097 first | second | gt2
3098 -------+--------+-----
3105 testdb=> \crosstabview first second
3106 first | one | two | three | four
3107 -------+-----+-----+-------+------
3114 This second example shows a multiplication table with rows sorted in
3115 reverse numerical order and columns with an independent, ascending
3117 testdb=> SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as
3119 testdb-> row_number() over(order by t2.first) AS ord
3120 testdb-> FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC
3121 testdb-> \crosstabview "A" "B" "AxB" ord
3122 A | 101 | 102 | 103 | 104
3123 ---+-----+-----+-----+-----
3124 4 | 404 | 408 | 412 | 416
3125 3 | 303 | 306 | 309 | 312
3126 2 | 202 | 204 | 206 | 208
3127 1 | 101 | 102 | 103 | 104