PSQL(1)
π NAME π
okay bestie, welcome to PSQL(1) β thatβs the PostgreSQL interactive terminal, and this is the PostgreSQL 14.24 Documentation vibes. psql is literally a terminal-based front-end to PostgreSQL. It lets you type in queries interactively, send them to PostgreSQL, and see the query results. You can also feed input in from a file or from command line arguments. On top of that, psql gives you a bunch of meta-commands and shell-like features so writing scripts and automating a whole variety of tasks is way easier. slay π
β¨ SYNOPSIS β¨
psql [option...] [dbname [username]]
π¦ DESCRIPTION π¦
psql is a terminal-based front-end to PostgreSQL. It enables you to type in queries interactively, issue them to PostgreSQL, and see the query results. Alternatively, input can be from a file or from command line arguments. In addition, psql provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks.
π OPTIONS π
-a,--echo-allβ print all nonempty input lines to standard output as they are read. (This does not apply to lines read interactively.) This is equivalent to setting the variableECHOtoall.-A,--no-alignβ switches to unaligned output mode. (The default output mode is aligned.) This is equivalent to\pset format unaligned.-b,--echo-errorsβ print failed SQL commands to standard error output. This is equivalent to setting the variableECHOtoerrors.-c command,--command=commandβ specifies thatpsqlis to execute the given command string, command. This option can be repeated and combined in any order with the-foption. When either-cor-fis specified,psqldoes not read commands from standard input; instead it terminates after processing all the-cand-foptions in sequence.
command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a -c option. To achieve that, you could use repeated -c options or pipe the string into psql, for example:
psql -c '\x' -c 'SELECT * FROM foo;'
or
echo '\x \\ SELECT * FROM foo;' | psql
(\\ is the separator meta-command.)
Each SQL command string passed to -c is sent to the server as a single request. Because of this, the server executes it as a single transaction even if the string contains multiple SQL commands, unless there are explicit BEGIN/COMMIT commands included in the string to divide it into multiple transactions. (See Section 53.2.2.1 for more details about how the server handles multi-query strings.) Also, psql only prints the result of the last SQL command in the string. This is different from the behavior when the same string is read from a file or fed to psql's standard input, because then psql sends each SQL command separately.
Because of this behavior, putting more than one SQL command in a single -c string often has unexpected results. Itβs better to use repeated -c commands or feed multiple commands to psql's standard input, either using echo as illustrated above, or via a shell here-document, for example:
psql <<EOF
\x
SELECT * FROM foo;
EOF
--csvβ switches to CSV (Comma-Separated Values) output mode. This is equivalent to\pset format csv.-d dbname,--dbname=dbnameβ specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line. The dbname can be a connection string. If so, connection string parameters will override any conflicting command line options.-e,--echo-queriesβ copy all SQL commands sent to the server to standard output as well. This is equivalent to setting the variableECHOtoqueries.-E,--echo-hiddenβ echo the actual queries generated by\dand other backslash commands. You can use this to studypsql's internal operations. This is equivalent to setting the variableECHO_HIDDENtoon.-f filename,--file=filenameβ read commands from the file filename, rather than standard input. This option can be repeated and combined in any order with the-coption. When either-cor-fis specified,psqldoes not read commands from standard input; instead it terminates after processing all the-cand-foptions in sequence. Except for that, this option is largely equivalent to the meta-command\i.
If filename is - (hyphen), then standard input is read until an EOF indication or \q meta-command. This can be used to intersperse interactive input with input from files. Note however that Readline is not used in this case (much as if -n had been specified).
Using this option is subtly different from writing psql < filename. In general, both will do what you expect, but using -f enables some nice features such as error messages with line numbers. There is also a slight chance that using this option will reduce the start-up overhead. On the other hand, the variant using the shellβs input redirection is (in theory) guaranteed to yield exactly the same output you would have received had you entered everything by hand.
-F separator,--field-separator=separatorβ use separator as the field separator for unaligned output. This is equivalent to\pset fieldsepor\f.-h hostname,--host=hostnameβ specifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix-domain socket.-H,--htmlβ switches to HTML output mode. This is equivalent to\pset format htmlor the\Hcommand.-l,--listβ list all available databases, then exit. Other non-connection options are ignored. This is similar to the meta-command\list.
When this option is used, psql will connect to the database postgres, unless a different database is named on the command line (option -d or non-option argument, possibly via a service entry, but not via an environment variable).
-L filename,--log-file=filenameβ write all query output into file filename, in addition to the normal output destination.-n,--no-readlineβ do not use Readline for line editing and do not use the command history. This can be useful to turn off tab expansion when cutting and pasting.-o filename,--output=filenameβ put all query output into file filename. This is equivalent to the command\o.-p port,--port=portβ specifies the TCP port or the local Unix-domain socket file extension on which the server is listening for connections. Defaults to the value of thePGPORTenvironment variable or, if not set, to the port specified at compile time, usually5432.-P assignment,--pset=assignmentβ specifies printing options, in the style of\pset. Note that here you have to separate name and value with an equal sign instead of a space. For example, to set the output format to LaTeX, you could write-P format=latex.-q,--quietβ specifies thatpsqlshould do its work quietly. By default, it prints welcome messages and various informational output. If this option is used, none of this happens. This is useful with the-coption. This is equivalent to setting the variableQUIETtoon.-R separator,--record-separator=separatorβ use separator as the record separator for unaligned output. This is equivalent to\pset recordsep.-s,--single-stepβ run in single-step mode. That means the user is prompted before each command is sent to the server, with the option to cancel execution as well. Use this to debug scripts.-S,--single-lineβ runs in single-line mode where a newline terminates an SQL command, as a semicolon does.
Note This mode is provided for those who insist on it, but you are not necessarily encouraged to use it. In particular, if you mix SQL and meta-commands on a line the order of execution might not always be clear to the inexperienced user.
-t,--tuples-onlyβ turn off printing of column names and result row count footers, etc. This is equivalent to\tor\pset tuples_only.-T table_options,--table-attr=table_optionsβ specifies options to be placed within the HTMLtabletag. See\pset tableattrfor details.-U username,--username=usernameβ connect to the database as the user username instead of the default. (You must have permission to do so, of course.)-v assignment,--set=assignment,--variable=assignmentβ perform a variable assignment, like the\setmeta-command. Note that you must separate name and value, if any, by an equal sign on the command line. To unset a variable, leave off the equal sign. To set a variable with an empty value, use the equal sign but leave off the value. These assignments are done during command line processing, so variables that reflect connection state will get overwritten later.-V,--versionβ print thepsqlversion and exit.-w,--no-passwordβ never issue a password prompt. If the server requires password authentication and a password is not available from other sources such as a.pgpassfile, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.
Note that this option will remain set for the entire session, and so it affects uses of the meta-command \connect as well as the initial connection attempt.
-W,--passwordβ forcepsqlto prompt for a password before connecting to a database, even if the password will not be used.
If the server requires password authentication and a password is not available from other sources such as a .pgpass file, psql will prompt for a password in any case. However, psql will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing -W to avoid the extra connection attempt.
Note that this option will remain set for the entire session, and so it affects uses of the meta-command \connect as well as the initial connection attempt.
-x,--expandedβ turn on the expanded table formatting mode. This is equivalent to\xor\pset expanded.-X,--no-psqlrcβ do not read the start-up file (neither the system-widepsqlrcfile nor the userβs~/.psqlrcfile).-z,--field-separator-zeroβ set the field separator for unaligned output to a zero byte. This is equivalent to\pset fieldsep_zero.-0,--record-separator-zeroβ sets the record separator for unaligned output to a zero byte π«§. This is literally so useful for interfacing, for example, withxargs -0. It's exactly equivalent to\pset recordsep_zero.-1,--single-transactionβ okay so this one can only be used in combination with one or more-cand/or-foptions, no solo runs bestie π . It makes psql issue aBEGINcommand before the first such option and aCOMMITcommand after the last one, wrapping all the commands into a single transaction. The whole point: either all the commands complete successfully, or no changes are applied. Iconic, honestly.
β οΈ But listen β if the commands themselves containBEGIN,COMMIT, orROLLBACK, this option will not have the desired effects. Also, if an individual command cannot be executed inside a transaction block, specifying this option will cause the whole transaction to fail. So likeβ¦ know your commands, bestie π.
-?,--help[=topic]β shows help about psql and exits π. The optional topic parameter (which defaults tooptions) picks which part of psql gets explained:commandsdescribes psql's backslash commands;optionsdescribes the command-line options that can be passed to psql; andvariablesshows help about psql configuration variables. Choose your own adventure β¨.
π₯ EXIT STATUS π₯
psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs (e.g., out of memory, file not found), 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set π.
π Pro tip from your girl: those numbers are your vibe check. 0 = slay, everything else = look at the error and fix it.
π USAGE π
πΈ Connecting to a Database πΈ
psql is a regular PostgreSQL client application, no cap. In order to connect to a database you need to know the name of your target database, the host name and port number of the server, and what user name you want to connect as. psql can be told about those parameters via command line options, namely -d, -h, -p, and -U respectively π«Ά. If an argument is found that does not belong to any option it will be interpreted as the database name (or the user name, if the database name is already given). Not all of these options are required; there are useful defaults π.
If you omit the host name, psql will connect via a Unix-domain socket to a server on the local host, or via TCP/IP to localhost on machines that don't have Unix-domain sockets. The default port number is determined at compile time. Since the database server uses the same default, you will not have to specify the port in most cases. The default user name is your operating-system user name, as is the default database name. Note that you cannot just connect to any database under any user name β your database administrator should have informed you about your access rights π
When the defaults aren't quite right, you can save yourself some typing by setting the environment variables PGDATABASE, PGHOST, PGPORT and/or PGUSER to appropriate values. (For additional environment variables, see Section 34.15.) It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 34.16 for more information π§.
An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism gives you very wide control over the connection. For example:
$ psql "service=myservice sslmode=require"
$ psql postgresql://dbmaster:5433/mydb?sslmode=require
This way you can also use LDAP for connection parameter lookup as described in Section 34.18. See Section 34.1.2 for more information on all the available connection options β¨.
If the connection could not be made for any reason (e.g., insufficient privileges, server is not running on the targeted host, etc.), psql will return an error and terminate. Rude, but fair π.
If both standard input and standard output are a terminal, then psql sets the client encoding to "auto", which will detect the appropriate client encoding from the locale settings (LC_CTYPE environment variable on Unix systems). If this doesn't work out as expected, the client encoding can be overridden using the environment variable PGCLIENTENCODING πΈ.
π¦ Entering SQL Commands π¦
In normal operation, psql provides a prompt with the name of the database to which psql is currently connected, followed by the string =>. For example:
$ psql testdb
psql (14.24)
Type "help" for help.
testdb=>
At the prompt, the user can type in SQL commands. Ordinarily, input lines are sent to the server when a command-terminating semicolon is reached. An end of line does not terminate a command π«§. Thus commands can be spread over several lines for clarity. If the command was sent and executed without error, the results of the command are displayed on the screen. Main character behavior, honestly π.
β οΈ If untrusted users have access to a database that has not adopted a secure schema usage pattern, begin your session by removing publicly-writable schemas fromsearch_path. One can addoptions=-csearch_path=to the connection string or issueSELECT pg_catalog.set_config('search_path', '', false)before other SQL commands. This consideration is not specific to psql; it applies to every interface for executing arbitrary SQL commands. Genuinely important, bestie β do not skip this one π.
Whenever a command is executed, psql also polls for asynchronous notification events generated by LISTEN and NOTIFY π.
While C-style block comments are passed to the server for processing and removal, SQL-standard comments are removed by psql π .
π Meta-Commands π
Anything you enter in psql that begins with an unquoted backslash is a psql meta-command that is processed by psql itself. These commands make psql more useful for administration or scripting. Meta-commands are often called slash or backslash commands π.
The format of a psql command is the backslash, followed immediately by a command verb, then any arguments. The arguments are separated from the command verb and each other by any number of whitespace characters β¨.
To include whitespace in an argument you can quote it with single quotes. To include a single quote in an argument, write two single quotes within single-quoted text. Anything contained in single quotes is furthermore subject to C-like substitutions for \n (new line), \t (tab), \b (backspace), \r (carriage return), \f (form feed), \digits (octal), and \xdigits (hexadecimal). A backslash preceding any other character within single-quoted text quotes that single character, whatever it is π.
If an unquoted colon (:) followed by a psql variable name appears within an argument, it is replaced by the variable's value, as described in SQL Interpolation below. The forms :'variable_name' and :"variable_name" described there work as well. The :{?variable_name} syntax allows testing whether a variable is defined. It is substituted by TRUE or FALSE. Escaping the colon with a backslash protects it from substitution πΈ.
Within an argument, text that is enclosed in backquotes (`) is taken as a command line that is passed to the shell. The output of the command (with any trailing newline removed) replaces the backquoted text. Within the text enclosed in backquotes, no special quoting or other processing occurs, except that appearances of :variable_name where variable_name is a psql variable name are replaced by the variable's value. Also, appearances of :'variable_name' are replaced by the variable's value suitably quoted to become a single shell command argument. (The latter form is almost always preferable, unless you are very sure of what is in the variable.) Because carriage return and line feed characters cannot be safely quoted on all platforms, the :'variable_name' form prints an error message and does not substitute the variable value when such characters appear in the value π₯.
Some commands take an SQL identifier (such as a table name) as argument. These arguments follow the syntax rules of SQL: Unquoted letters are forced to lowercase, while double quotes (") protect letters from case conversion and allow incorporation of whitespace into the identifier. Within double quotes, paired double quotes reduce to a single double quote in the resulting name. For example, FOO"BAR"BAZ is interpreted as fooBARbaz, and "A weird"" name" becomes A weird" name π¦.
Parsing for arguments stops at the end of the line, or when another unquoted backslash is found. An unquoted backslash is taken as the beginning of a new meta-command. The special sequence \\ (two backslashes) marks the end of arguments and continues parsing SQL commands, if any. That way SQL and psql commands can be freely mixed on a line. But in any case, the arguments of a meta-command cannot continue beyond the end of the line π.
Many of the meta-commands act on the current query buffer. This is simply a buffer holding whatever SQL command text has been typed but not yet sent to the server for execution. This will include previous input lines as well as any text appearing before the meta-command on the same line π«.
The following meta-commands are defined:
\a
If the current table output format is unaligned, it is switched to aligned. If it is not unaligned, it is set to unaligned. This command is kept for backwards compatibility. See \pset for a more general solution π.
\c or \connect
\c or \connect [ -reuse-previous=on|off ] [ dbname [ username ] [ host ] [ port ] | conninfo ]
Establishes a new connection to a PostgreSQL server. The connection parameters to use can be specified either using a positional syntax (one or more of database name, user, host, and port), or using a conninfo connection string as detailed in Section 34.1.1. If no arguments are given, a new connection is made using the same parameters as before π«Ά.
Specifying any of dbname, username, host or port as - is equivalent to omitting that parameter π
.
The new connection can re-use connection parameters from the previous connection; not only database name, user, host, and port, but other settings such as sslmode. By default, parameters are re-used in the positional syntax, but not when a conninfo string is given. Passing a first argument of -reuse-previous=on or -reuse-previous=off overrides that default. If parameters are re-used, then any parameter not explicitly specified as a positional parameter or in the conninfo string is taken from the existing connection's parameters. An exception is that if the host setting is changed from its previous value using the positional syntax, any hostaddr setting present in the existing connection's parameters is dropped. Also, any password used for the existing connection will be re-used only if the user, host, and port settings are not changed. When the command neither specifies nor reuses a particular parameter, the libpq default is used β¨.
Okay so if the new connection actually goes through? The old one gets closed, bye. π
But if the connection attempt fails (wrong user name, access denied, etc.), the old connection is kept β but only if psql is in interactive mode. In a non-interactive script though? The old connection is closed and an error is reported. That may or may not terminate the script; and if it doesn't, like, every database-accessing command will fail until another \connect command is successfully executed π. This distinction was chosen as a user convenience against typos on the one hand, and a safety mechanism that scripts are not accidentally acting on the wrong database on the other hand. Also β important β whenever a \connect command attempts to re-use parameters, the values re-used are those of the last successful connection, not of any failed attempts made subsequently. However, in the case of a non-interactive \connect failure, no parameters are allowed to be re-used later, since the script would likely be expecting the values from the failed \connect to be re-used. no cap π«Ά
Examples (iconic, memorize them):
=> \c mydb myuser host.dom 6432
=> \c service=foo
=> \c "host=localhost port=5432 dbname=mydb connect_timeout=10 sslmode=disable"
=> \c -reuse-previous=on sslmode=require -- changes only sslmode
=> \c postgresql://tom@localhost/mydb?application_name=myapp
π \C [ title ]
Sets the title of any tables being printed as the result of a query β or unsets any such title if you don't give one. This command is literally equivalent to \pset title title. (Fun lore: the name of this command derives from "caption", because it was previously only used to set the caption in an HTML table. history π)
π¦ \cd [ directory ]
Changes the current working directory to directory. Without an argument, it changes to the current user's home directory. cute.
Tip β To print your current working directory, use \! pwd. π«Ά
πΈ \conninfo
Outputs info about the current database connection. That's it, that's the whole vibe check. β¨
π \copy { table [ ( column_list ) ] } from { 'filename' | program 'command' | stdin | pstdin } [ [ with ] ( option [, ...] ) ] [ where condition ]
π \copy { table [ ( column_list ) ] | ( query ) } to { 'filename' | program 'command' | stdout | pstdout } [ [ with ] ( option [, ...] ) ]
Performs a frontend (client) copy. Bestie this is the whole thing: it runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. Which means the file accessibility and privileges are those of the local user, not the server β and no SQL superuser privileges are required. lowkey a slay π₯
When program is specified, command is executed by psql and the data passed from or to command is routed between the server and the client. Again, the execution privileges are those of the local user, not the server, and no SQL superuser privileges are required.
For \copy ... from stdin, data rows are read from the same source that issued the command, continuing until \. is read or the stream reaches EOF. This option is useful for populating tables in-line within an SQL script file π. For \copy ... to stdout, output is sent to the same place as psql command output, and the COPY count command status is not printed (since it might be confused with a data row β awkward π¬). To read/write psql's standard input or output regardless of the current command source or \o option, write from pstdin or to pstdout.
The syntax of this command is similar to that of the SQL COPY command. All options other than the data source/destination are as specified for COPY. Because of this, special parsing rules apply to the \copy meta-command: unlike most other meta-commands, the entire remainder of the line is always taken to be the arguments of \copy, and neither variable interpolation nor backquote expansion are performed in the arguments. periodt.
Tip β Another way to get the same result as\copy ... tois to use the SQLCOPY ... TO STDOUTcommand and terminate it with\g filenameor\g |program. Unlike\copy, this method lets the command span multiple lines; also, variable interpolation and backquote expansion can be used. β
Tip β Heads up, these operations are not as efficient as the SQLCOPYcommand with a file or program data source or destination, because all data must pass through the client/server connection π. For large amounts of data the SQL command might be preferable. Also, because of this pass-through method,\copy ... fromin CSV mode will erroneously treat a\.data value alone on a line as an end-of-input marker. fr fr watch out.
π§ \copyright
Shows the copyright and distribution terms of PostgreSQL. legal era π
π \crosstabview [ colV [ colH [ colD [ sortcolH ] ] ] ]
Executes the current query buffer (like \g) and shows the results in a crosstab grid. The query must return at least three columns. The output column identified by colV becomes a vertical header and the output column identified by colH becomes a horizontal header. colD identifies the output column to display within the grid. sortcolH identifies an optional sort column for the horizontal header.
Each column specification can be a column number (starting at 1) or a column name. The usual SQL case folding and quoting rules apply to column names. If omitted, colV is taken as column 1 and colH as column 2. colH must differ from colV. If colD is not specified, then there must be exactly three columns in the query result, and the column that is neither colV nor colH is taken to be colD.
The vertical header, displayed as the leftmost column, contains the values found in column colV, in the same order as in the query results, but with duplicates removed β¨.
The horizontal header, displayed as the first row, contains the values found in column colH, with duplicates removed. By default, these appear in the same order as in the query results. But if the optional sortcolH argument is given, it identifies a column whose values must be integer numbers, and the values from colH will appear in the horizontal header sorted according to the corresponding sortcolH values.
Inside the crosstab grid, for each distinct value x of colH and each distinct value y of colV, the cell located at the intersection (x,y) contains the value of the colD column in the query result row for which the value of colH is x and the value of colV is y. If there is no such row, the cell is empty. If there are multiple such rows, an error is reported π.
π \d[S+] [ pattern ]
For each relation (table, view, materialized view, index, sequence, or foreign table) or composite type matching the pattern, show all columns, their types, the tablespace (if not the default) and any special attributes such as NOT NULL or defaults. Associated indexes, constraints, rules, and triggers are also shown. For foreign tables, the associated foreign server is shown as well. ("Matching the pattern" is defined in Patterns below, iykyk.)
For some types of relation, \d shows additional information for each column: column values for sequences, indexed expressions for indexes, and foreign data wrapper options for foreign tables. extra tea β
The command form \d+ is identical, except that more information is displayed: any comments associated with the columns of the table are shown, as is the presence of OIDs in the table, the view definition if the relation is a view, a non-default replica identity setting and the access method name if the relation has an access method.
By default, only user-created objects are shown; supply a pattern or the S modifier to include system objects.
Note β If\dis used without a pattern argument, it is equivalent to\dtvmsE, which will show a list of all visible tables, views, materialized views, sequences and foreign tables. This is purely a convenience measure π.
π \da[S] [ pattern ]
Lists aggregate functions, together with their return type and the data types they operate on. If pattern is specified, only aggregates whose names match the pattern are shown. By default, only user-created objects are shown; supply a pattern or the S modifier to include system objects.
π¦ \dA[+] [ pattern ]
Lists access methods. If pattern is specified, only access methods whose names match the pattern are shown. If + is appended to the command name, each access method is listed with its associated handler function and description. π
π \dAc[+] [access-method-pattern [input-type-pattern]]
Lists operator classes (see Section 38.16.1). If access-method-pattern is specified, only operator classes associated with access methods whose names match that pattern are listed. If input-type-pattern is specified, only operator classes associated with input types whose names match that pattern are listed. If + is appended to the command name, each operator class is listed with its associated operator family and owner.
π \dAf[+] [access-method-pattern [input-type-pattern]]
Lists operator families (see Section 38.16.5). If access-method-pattern is specified, only operator families associated with access methods whose names match that pattern are listed. If input-type-pattern is specified, only operator families associated with input types whose names match that pattern are listed. If + is appended to the command name, each operator family is listed with its owner.
π \dAo[+] [access-method-pattern [operator-family-pattern]]
Lists operators associated with operator families (see Section 38.16.2). If access-method-pattern is specified, only members of operator families associated with access methods whose names match that pattern are listed. If operator-family-pattern is specified, only members of operator families whose names match that pattern are listed. If + is appended to the command name, each operator is listed with its sort operator family (if it is an ordering operator). β¨
\dAp[+] [access-method-pattern [operator-family-pattern]]β lists the support functions that belong to operator families (peep Section 38.16.3 for the lore π ). Pass access-method-pattern and it only shows functions of operator families attached to access methods whose names match that pattern. Pass operator-family-pattern and it only shows functions of operator families whose names match that pattern. Stick a+on the command name and it goes verbose mode, showing the actual parameter lists β no cap, that's the good stuff.\db[+] [ pattern ]β lists tablespaces. Give it a pattern and only tablespaces whose names match show up. Add+and each tablespace comes with its associated options, on-disk size, permissions, and description. it's giving full audit energy β¨\dc[S+] [ pattern ]β lists conversions between character-set encodings. pattern filters by name. By default only user-created objects are shown, so supply a pattern or theSmodifier to include system objects. Add+and each object is listed with its associated description.\dC[+] [ pattern ]β lists type casts. If pattern is specified, only casts whose source or target types match the pattern are listed. Add+and each object gets its associated description too.\dd[S] [ pattern ]β shows the descriptions of objects of type constraint, operator class, operator family, rule, and trigger. All the other comments can be viewed with the respective backslash commands for those object types (iykyk).
\dd displays descriptions for objects matching the pattern, or for visible objects of the appropriate type if you give it no argument. But either way, only objects that actually have a description are listed. By default only user-created objects are shown β supply a pattern or the S modifier to include system objects.
Descriptions for objects can be created with the COMMENT SQL command. π«Ά
\dD[S+] [ pattern ]β lists domains. pattern filters by name. By default only user-created objects show up; supply a pattern or theSmodifier to include system objects. Add+and each object is listed with its associated permissions and description.\ddp [ pattern ]β lists default access privilege settings. An entry is shown for each role (and schema, if applicable) for which the default privilege settings have been changed from the built-in defaults. Give it a pattern and only entries whose role name or schema name matches are listed.
The ALTER DEFAULT PRIVILEGES command is what sets default access privileges, and the meaning of the privilege display is explained in Section 5.7. π
\dE[S+] [ pattern ],\di[S+] [ pattern ],\dm[S+] [ pattern ],\ds[S+] [ pattern ],\dt[S+] [ pattern ],\dv[S+] [ pattern ]β bestie this is a whole squad of commands, and the lettersE,i,m,s,t, andvstand for foreign table, index, materialized view, sequence, table, and view, respectively. You can specify any or all of these letters, in any order, to get a listing of objects of those types. For example,\dtilists tables and indexes β iconic combo honestly.
Add + and each object is listed with its persistence status (permanent, temporary, or unlogged), physical size on disk, and associated description if any. Give it a pattern and only objects whose names match are listed. By default only user-created objects are shown; supply a pattern or the S modifier to include system objects. π
\des[+] [ pattern ]β lists foreign servers (mnemonic: "external servers" π). Give it a pattern and only servers whose name matches are listed. Use the form\des+and you get a full description of each server, including the server's access privileges, type, version, options, and description. full main character reveal.\det[+] [ pattern ]β lists foreign tables (mnemonic: "external tables"). With a pattern, only entries whose table name or schema name matches are listed. Use\det+and generic options plus the foreign table description also show up.\deu[+] [ pattern ]β lists user mappings (mnemonic: "external users"). Give it a pattern and only mappings whose user names match are listed. The form\deu+shows additional information about each mapping. π
β οΈ Caution bestie: \deu+ might also display the user name and password of the remote user, so be careful not to disclose them. like genuinely, protect that info π
\dew[+] [ pattern ]β lists foreign-data wrappers (mnemonic: "external wrappers"). With a pattern, only foreign-data wrappers whose name matches are listed. The form\dew+also shows the access privileges, options, and description of the foreign-data wrapper.\df[anptwS+] [ pattern [ arg_pattern ... ] ]β lists functions, together with their result data types, argument data types, and function types, which are classified as "agg" (aggregate), "normal", "procedure", "trigger", or "window". To display only functions of specific type(s), add the corresponding lettersa,n,p,t, orwto the command. Give it a pattern and only functions whose names match are shown.
Any additional arguments are type-name patterns, matched to the type names of the first, second, and so on arguments of the function. (Matching functions can have more arguments than the ones you specify β to prevent that, write a dash - as the last arg_pattern.) By default only user-created objects are shown; supply a pattern or the S modifier to include system objects.
The form \df+ shows additional information about each function, including volatility, parallel safety, owner, security classification, access privileges, language, source code and description. that's the deep dive, we love to see it π₯
\dF[+] [ pattern ]β lists text search configurations. pattern filters by name. The form\dF+shows a full description of each configuration, including the underlying text search parser and the dictionary list for each parser token type.\dFd[+] [ pattern ]β lists text search dictionaries. pattern filters by name. The form\dFd+shows additional information about each selected dictionary, including the underlying text search template and the option values. π\dFp[+] [ pattern ]β lists text search parsers. pattern filters by name. The form\dFp+shows a full description of each parser, including the underlying functions and the list of recognized token types.\dFt[+] [ pattern ]β lists text search templates. pattern filters by name. The form\dFt+shows additional information about each template, including the underlying function names.\dg[S+] [ pattern ]β lists database roles. (Since the concepts of "users" and "groups" have been unified into "roles", this command is now equivalent to\duβ glow-up era π .) By default only user-created roles are shown; supply theSmodifier to include system roles. Give it a pattern and only roles whose names match are listed. The form\dg+shows additional information about each role β currently this adds the comment for each role.\dlβ this is literally an alias for\lo_list, which shows a list of large objects. short and sweet.\dL[S+] [ pattern ]β lists procedural languages. pattern filters by name. By default only user-created languages are shown; supply theSmodifier to include system objects. Add+and each language is listed with its call handler, validator, access privileges, and whether it is a system object.\dn[S+] [ pattern ]β lists schemas (namespaces). pattern filters by name. By default only user-created objects are shown; supply a pattern or theSmodifier to include system objects. Add+and each object is listed with its associated permissions and description, if any. β¨\do[S+] [ pattern [ arg_pattern [ arg_pattern ] ] ]β lists operators with their operand and result types. Give it a pattern and only operators whose names match are listed. If one arg_pattern is specified, only prefix operators whose right argument's type name matches that pattern are listed. If two arg_patterns are specified, only binary operators whose argument type names match those patterns are listed. (Alternatively, write-for the unused argument of a unary operator.)
By default only user-created objects are shown; supply a pattern or the S modifier to include system objects. Add + and you get additional information about each operator β currently just the name of the underlying function. π¦
\dO[S+] [ pattern ]β lists collations. pattern filters by name. By default only user-created objects are shown; supply a pattern or theSmodifier to include system objects. Add+and each collation is listed with its associated description, if any.
π Little heads up: only collations usable with the current database's encoding are shown, so the results may vary in different databases of the same installation. no cap, that's just how it is.
\dp [ pattern ]β lists tables, views and sequences with their associated access privileges. Give it a pattern and only tables, views and sequences whose names match are listed.
The GRANT and REVOKE commands are used to set access privileges, and the meaning of the privilege display is explained in Section 5.7. π
π
\dP[itn+] [ pattern ]
Lists out your partitioned relations, bestie. If you give it a pattern, only the entries whose names match that pattern get listed β no pattern, no filter, we're seeing everybody.
The modifiers t (tables) and i (indexes) can be tacked onto the command to filter which kind of relations show up. And by default? Partitioned tables and indexes are the ones listed.
If you use the modifier n ("nested"), or you specify a pattern, then the non-root partitioned relations get included too, and you get a whole extra column showing the parent of each partitioned relation. Family tree realness π³
If you slap a + on the end of the command name, you also get the sum of the sizes of each relation's partitions, plus the relation's description. And if you combine n with +, you get two sizes, not one:
- one that includes the total size of directly-attached leaf partitions
- another showing the total size of all partitions, including indirectly attached sub-partitions
Two sizes. She contains multitudes. π
ποΈ \drds [ role-pattern [ database-pattern ] ]
Lists all your defined configuration settings, bestie. These bad boys can be role-specific, database-specific, or honestly both at once β she's flexible like that.
role-pattern and database-pattern are how you pick which specific roles and databases to list, respectively. Omit them, or pass *, and all the settings get listed β including the ones that aren't role-specific or database-specific, respectively.
Heads up: theALTER ROLEandALTER DATABASEcommands are what you use to define per-role and per-database configuration settings. That's where these come from π
π \dRp[+] [ pattern ]
Lists replication publications. Pass a pattern and only the publications whose names match get listed. Append + to the command name and the tables associated with each publication are shown too β the whole guest list, no cap. β¨
π¬ \dRs[+] [ pattern ]
Lists replication subscriptions. Same deal: give it a pattern and only matching subscription names come through. Append + and you get additional properties of the subscriptions shown as well. Extra lore unlocked π«Ά
π¨ \dT[S+] [ pattern ]
Lists your data types. With a pattern, only the types whose names match get listed.
Append + and each type comes with its internal name and size, its allowed values if it happens to be an enum type, and its associated permissions. Full dossier energy π
By default, only user-created objects are shown β so if you want the system objects in there, supply a pattern or the S modifier.
π₯ \du[S+] [ pattern ]
Lists database roles. And yes, since the concepts of "users" and "groups" got unified into "roles", this command is now literally equivalent to \dg. Same thing, different name.
By default only user-created roles show up; hand it the S modifier to include system roles too. Give it a pattern and only the roles whose names match are listed.
Use the \du+ form and you get additional information about each role β currently that adds the comment for each role. π
π§© \dx[+] [ pattern ]
Lists installed extensions. pattern filters by name, obviously. Use \dx+ and all the objects belonging to each matching extension get listed too β the full contents of the bag, spilled out. π
π \dX [ pattern ]
Lists extended statistics. Give it a pattern and only the extended statistics whose names match are listed.
Each kind of extended statistics gets its status shown in a column named after its statistic kind (e.g. Ndistinct). What do the values mean?
definedβ it was requested when creating the statisticsNULLβ it wasn't requested
And if you're nosy and want to know whether ANALYZE was run and whether statistics are actually available to the planner? Use pg_stats_ext. That's the tea β
β‘ \dy[+] [ pattern ]
Lists event triggers. pattern filters by name like always. Append + to the command name and each object gets listed with its associated description. π
βοΈ \e or \edit [ filename ] [ line_number ]
Okay so this is the editor one, and she's iconic. Let's break it down:
- If filename is specified, that file gets edited. After your editor exits, the file's content is copied into the current query buffer.
- If no filename is given, the current query buffer gets copied to a temporary file, which is then edited in the same fashion.
- Or, if the current query buffer is empty, the most recently executed query gets copied to a temporary file and edited in the same fashion.
Now the important bit π
If you edit a file or the previous query and you quit the editor without modifying the file, the query buffer is cleared. Otherwise, the new contents of the query buffer get re-parsed according to the normal rules of psql, treating the whole buffer as a single line.
Any complete queries are immediately executed β meaning if the query buffer contains or ends with a semicolon, everything up to that point is executed and removed from the query buffer. Whatever's left in the buffer is redisplayed. Type semicolon or \g to send it, or \r to cancel it by clearing the query buffer.
Treating the buffer as a single line primarily affects meta-commands: whatever is in the buffer after a meta-command will be taken as argument(s) to the meta-command, even if it spans multiple lines. (So no, you cannot make meta-command-using scripts this way. Use \i for that. π
)
If a line_number is specified, psql positions the cursor on that specified line of the file or query buffer. And note this: if a single all-digits argument is given, psql assumes it's a line number, not a file name.
π‘ Tip β See Environment, below, for how to configure and customize your editor.
π£οΈ \echo text [ ... ]
Prints the evaluated arguments to standard output, separated by spaces and followed by a newline. Genuinely useful for sprinkling little bits of info into the output of your scripts. Like this:
=> \echo `date`
Tue Oct 26 21:40:57 CEST 1999
If the first argument is an unquoted -n, the trailing newline is not written (and neither is the first argument, obviously).
π‘ Tip β If you're using the\ocommand to redirect your query output, you might wanna use\qechoinstead of this one. Also see\warn. π«Ά
π§ͺ \ef [ function_description [ line_number ] ]
This one fetches and edits the definition of the named function or procedure, in the form of a CREATE OR REPLACE FUNCTION or CREATE OR REPLACE PROCEDURE command. Editing works the exact same way as for \edit.
- Quit the editor without saving β the statement is discarded.
- Save and exit the editor β the updated command is executed immediately if you added a semicolon to it. Otherwise it gets redisplayed; type semicolon or
\gto send it, or\rto cancel.
The target function can be specified by name alone, or by name and arguments, like foo(integer, text). You must give the argument types if there's more than one function with the same name.
No function specified? You get a blank CREATE FUNCTION template to edit. Blank canvas, main character energy π¨
If a line_number is specified, psql positions the cursor on that specified line of the function body. (Note that the function body typically doesn't begin on the first line of the file, jsyk.)
And here's the quirky part: unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \ef, and neither variable interpolation nor backquote expansion is performed in the arguments. That's just how she is π
π‘ Tip β See Environment, below, for how to configure and customize your editor.
π€ \encoding [ encoding ]
Sets the client character set encoding. No argument? Then this command just shows you the current encoding. Peek-a-boo π
π \errverbose
Repeats the most recent server error message at maximum verbosity, as though VERBOSITY were set to verbose and SHOW_CONTEXT were set to always. For when you need the whole entire story, not the summary. Give me every detail, I want the director's cut. π
πͺ \ev [ view_name [ line_number ] ]
Fetches and edits the definition of the named view, in the form of a CREATE OR REPLACE VIEW command. Editing is done the same way as for \edit:
- Quit the editor without saving β statement discarded. Bye π
- Save and exit β the updated command executes immediately if you added a semicolon to it. Otherwise it's redisplayed; type semicolon or
\gto send it, or\rto cancel.
No view specified? Blank CREATE VIEW template, presented for editing. π
If a line_number is specified, psql positions the cursor on that specified line of the view definition.
And same energy as \ef: unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \ev, and neither variable interpolation nor backquote expansion is performed in the arguments.
π \f [ string ]
Sets the field separator for unaligned query output. The default is the vertical bar (|). It's equivalent to \pset fieldsep. Short and sweet, we love her πΈ
π \g [ (option=value [...]) ] [ filename ]
π \g [ (option=value [...]) ] [ |command ]
Sends the current query buffer to the server for execution. The moment we've all been waiting for π₯
If parentheses appear after \g, they surround a space-separated list of option=value formatting-option clauses, which get interpreted the same way as \pset option value commands β but they only take effect for the duration of this query. One-shot glow-up β¨
In that list:
- spaces are not allowed around
=signs - spaces are required between option clauses
- if
=valueis omitted, the named option is changed in the same way as for\pset optionwith no explicit value
If a filename or |command argument is given, the query's output gets written to the named file or piped to the given shell command, instead of being displayed as usual. And here's the catch: the file or command is written to only if the query successfully returns zero or more tuples β not if the query fails, and not if it's a non-data-returning SQL command. Know the difference, bestie π«Ά
If the current query buffer is empty, the most recently sent query is re-executed instead. Except for that behavior, \g without any arguments is essentially equivalent to a semicolon. With arguments, \g gives you a "one-shot" alternative to the \o command, and additionally allows one-shot adjustments of the output formatting options normally set by \pset. Convenient? Insanely. π
When the last argument begins with |, the entire remainder of the line is taken to be the command to execute, and neither variable interpolation nor backquote expansion is performed in it. The rest of the line is simply passed literally to the shell. No editing, no translating β straight through π
\gdescβ okay so this one is a total vibe check for your query without actually running it π it shows you the description of the result of whatever's sitting in your current query buffer β meaning the column names and data types. The query is not actually executed, but heads up: if it's got some type of syntax error, that error will still get reported in the normal way. Rude but fair.
If your current query buffer is empty, it describes the most recently sent query instead. Convenient π
\gexecβ this is the main character command fr fr π it sends your current query buffer to the server, then treats each column of each row of the query's output (if any) as an SQL statement to execute. So you're basically generating queries with a query. Iconic.
Like, say you want to create an index on each column of my_table:
=> SELECT format('create index on my_table(%I)', attname)
-> FROM pg_attribute
-> WHERE attrelid = 'my_table'::regclass AND attnum > 0
-> ORDER BY attnum
-> \gexec
CREATE INDEX
CREATE INDEX
CREATE INDEX
CREATE INDEX
The generated queries get executed in the order the rows come back, and left-to-right within each row if there's more than one column. NULL fields are ignored, no stress. The generated queries are sent literally to the server for processing, so they can't be psql meta-commands and they can't contain psql variable references β them's the rules π«Ά
If any individual query fails, execution of the remaining queries continues unless ON_ERROR_STOP is set. Execution of each query is subject to ECHO processing (and setting ECHO to all or queries is often advisable when you're using \gexec). Query logging, single-step mode, timing, and other query execution features apply to each generated query as well β¨
If the current query buffer is empty, the most recently sent query is re-executed instead.
\gset [ prefix ]β sends your current query buffer to the server and stashes the query's output into psql variables (see Variables below). The query has to return exactly one row β no more, no less, bestie π Each column of that row gets stored into a separate variable, named the same as the column. Like:
=> SELECT 'hello' AS var1, 10 AS var2
-> \gset
=> \echo :var1 :var2
hello 10
If you specify a prefix, that string gets prepended to the query's column names to make the variable names you actually use:
=> SELECT 'hello' AS var1, 10 AS var2
-> \gset result_
=> \echo :result_var1 :result_var2
hello 10
If a column result is NULL, the corresponding variable gets unset rather than set. And if the query fails or doesn't return one row, no variables are changed at all β nothing happens, we move on π
If the current query buffer is empty, the most recently sent query is re-executed instead.
\gx [ (option=value [...]) ] [ filename ]\gx [ (option=value [...]) ] [ |command ]β\gxis literally just\gbut it forces expanded output mode for this query, as ifexpanded=onwere included in the list of\psetoptions. See also\xπ¦\hor\help [ command ]β gives you syntax help on the specified SQL command. If command isn't specified, psql lists all the commands it has syntax help for. And if command is an asterisk (*), you get syntax help on all SQL commands. The whole encyclopedia, slay π
Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \help, and neither variable interpolation nor backquote expansion is performed in the arguments. Just so you know.
Note: to simplify typing, commands that consist of several words don't have to be quoted. So it's totally fine to type \help alter table. π
\Hor\htmlβ turns on HTML query output format. And if the HTML format is already on, it switches back to the default aligned text format β it's a toggle, bestie. This command is for compatibility and convenience, but see\psetabout setting other output options π\ior\include filenameβ reads input from the file filename and executes it as though it had been typed on the keyboard. Like, manifesting the keystrokes β¨
If filename is - (hyphen), then standard input is read until an EOF indication or \q meta-command. This can be used to intersperse interactive input with input from files. Note that Readline behavior will be used only if it is active at the outermost level.
Note: if you want to see the lines on the screen as they're read, you must set the variableECHOtoall.
\if expression\elif expression\else\endifβ this whole group implements nestable conditional blocks, and honestly it's giving programming language πΈ A conditional block must begin with an\ifand end with an\endif. In between there can be any number of\elifclauses, which may optionally be followed by a single\elseclause. Ordinary queries and other types of backslash commands may (and usually do) appear between the commands forming a conditional block.
The \if and \elif commands read their argument(s) and evaluate them as a Boolean expression. If the expression yields true, processing continues normally; otherwise, lines get skipped until a matching \elif, \else, or \endif is reached. Once an \if or \elif test has succeeded, the arguments of later \elif commands in the same block are not evaluated but are treated as false. Lines following an \else are processed only if no earlier matching \if or \elif succeeded.
The expression argument of an \if or \elif command is subject to variable interpolation and backquote expansion, just like any other backslash command argument. After that it's evaluated like the value of an on/off option variable. So a valid value is any unambiguous case-insensitive match for one of: true, false, 1, 0, on, off, yes, no. For example, t, T, and tR will all be considered to be true π
Expressions that don't properly evaluate to true or false will generate a warning and be treated as false. Not me being ambiguous and getting banished to the false pile π
Lines being skipped are parsed normally to identify queries and backslash commands, but queries are not sent to the server, and backslash commands other than conditionals (\if, \elif, \else, \endif) are ignored. Conditional commands are checked only for valid nesting. Variable references in skipped lines are not expanded, and backquote expansion is not performed either.
All the backslash commands of a given conditional block must appear in the same source file. If EOF is reached on the main input file or an \include-ed file before all local \if-blocks have been closed, then psql will raise an error π¨
Here's an example, and yes it's a whole moment:
-- check for the existence of two separate records in the database and store
-- the results in separate psql variables
SELECT
EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer,
EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee
\gset
\if :is_customer
SELECT * FROM customer WHERE customer_id = 123;
\elif :is_employee
\echo 'is not a customer but is an employee'
SELECT * FROM employee WHERE employee_id = 456;
\else
\if yes
\echo 'not a customer or employee'
\else
\echo 'this will never print'
\endif
\endif
\iror\include_relative filenameβ the\ircommand is similar to\i, but it resolves relative file names differently. When executing in interactive mode, the two commands behave identically. But when invoked from a script,\irinterprets file names relative to the directory in which the script is located, rather than the current working directory. Sneaky but genius π§\l[+]or\list[+] [ pattern ]β lists the databases in the server and shows their names, owners, character set encodings, and access privileges. If pattern is specified, only databases whose names match the pattern get listed. And if+is appended to the command name, database sizes, default tablespaces, and descriptions are also displayed π
Size information is available for databases on which the current user has CONNECT privilege, or if the current user is a superuser or has privileges of the pg_read_all_stats role.
\lo_export loid filenameβ reads the large object with OID loid from the database and writes it to filename. Note that this is subtly different from the server functionlo_export, which acts with the permissions of the user that the database server runs as and on the server's file system. Different lane, different rules π«Ά
Tip: use \lo_list to find out the large object's OID.
\lo_import filename [ comment ]β stores the file into a PostgreSQL large object. Optionally, it associates the given comment with the object. Example:
foo=> \lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'
lo_import 152801
The response indicates that the large object received object ID 152801, which can be used to access the newly-created large object in the future. For the sake of readability, it's recommended to always associate a human-readable comment with every object β future you will be so grateful π Both OIDs and comments can be viewed with the \lo_list command.
Note that this command is subtly different from the server-side lo_import because it acts as the local user on the local file system, rather than the server's user and file system.
\lo_listβ shows a list of all PostgreSQL large objects currently stored in the database, along with any comments provided for them. A whole little gallery π\lo_unlink loidβ deletes the large object with OID loid from the database. Gone, reduced to atoms π
Tip: use \lo_list to find out the large object's OID.
\oor\out [ filename ]\oor\out [ |command ]β arranges to save future query results to the file filename or pipe future results to the shell command command. If no argument is specified, the query output is reset to the standard output. Back to default, no cap β¨
If the argument begins with |, then the entire remainder of the line is taken to be the command to execute, and neither variable interpolation nor backquote expansion is performed in it. The rest of the line is simply passed literally to the shell.
"Query results" includes all tables, command responses, and notices obtained from the database server, as well as output of various backslash commands that query the database (such as \d); but not error messages. Errors stay loud and visible, as they should π
Tip: to intersperse text output in between query results, use \qecho.
\por\printβ prints whatever's chillin' in your current query buffer straight to standard output. π And if the buffer's empty? No worries bestie, it just prints the most recently executed query instead. Iconic fallback behaviour honestly.\password[ username ] β changes the password of the user you name (or the current user if you don't name anyone). Here's the slay part: it prompts you for the new password, encrypts it, and ships it off to the server as anALTER ROLEcommand. The whole point is making sure your shiny new password never shows up in cleartext in the command history, the server log, or literally anywhere else. π Privacy queen.\prompt[ text ] name β prompts you to type in some text, and that text gets assigned to the variable name. You can optionally give it a prompt string, text. (Heads up: if your prompt has multiple words, wrap the text in single quotes, okay?) π«Ά
By default \prompt uses the terminal for input and output. But β plot twist β if the -f command line switch was used, then \prompt uses standard input and standard output instead. β¨
\pset[ option [ value ] ] β this is the one that sets all the options affecting how your query result tables get printed. option says which one you're setting, and the semantics of value kinda depend on which option you picked. For some options, leaving value out toggles the option or unsets it, as described under that particular option. And if there's no such behaviour mentioned? Then omitting value just displays the current setting. Simple as that. π
\pset with zero arguments displays the current status of all the printing options β a full vibe check of your table setup.
The adjustable printing options are:
borderβ value's gotta be a number. Generally, the higher the number, the more borders and lines your tables get, but the details depend on the format. In HTML format this translates directly into theborder=...attribute. In most other formats only0(no border),1(internal dividing lines), and2(table frame) make sense, and anything above2gets treated the same asborder = 2. Thelatexandlatex-longtableformats additionally allow a value of3to add dividing lines between data rows. πΌοΈcolumnsβ sets the target width for thewrappedformat, and also the width limit for deciding whether output is wide enough to need the pager or to switch to the vertical display inexpanded automode. Zero (the default) means the target width is controlled by the environment variableCOLUMNS, or by the detected screen width ifCOLUMNSisn't set. Also β ifcolumnsis zero then thewrappedformat only affects screen output. Ifcolumnsis nonzero then file and pipe output gets wrapped to that width too. πcsv_fieldsepβ specifies the field separator used inCSVoutput format. If the separator character shows up inside a field's value, that field gets output inside double quotes, following standard CSV rules. Default is a comma. πexpanded(orx) β if you give a value it has to be eitheronoroff, which enables or disables expanded mode, orauto. If you omit value the command toggles between theonandoffsettings. When expanded mode is on, query results display in two columns β column name on the left, data on the right. Super useful when the data just wouldn't fit on screen in the normal "horizontal" mode. In theautosetting, expanded mode is used whenever the query output has more than one column and is wider than the screen; otherwise the regular mode is used. Theautosetting is only effective in thealignedandwrappedformats. In other formats it always behaves as if expanded mode isoff. πfieldsepβ specifies the field separator used inunalignedoutput format. That way you can create, like, tab-separated output which other programs might prefer. To set a tab as the field separator, type\pset fieldsep '\t'. The default field separator is'|'(a vertical bar). πfieldsep_zeroβ sets the field separator used inunalignedoutput format to a zero byte. π«§footerβ if you give a value it must be eitheronoroff, which enables or disables display of the table footer (that(n rows)count). If value is omitted the command toggles footer displayonoroff. π’formatβ sets the output format to one ofaligned,asciidoc,csv,html,latex,latex-longtable,troff-ms,unaligned, orwrapped. Unique abbreviations are allowed. β¨
aligned format is the standard, human-readable, nicely formatted text output; this is the default. π
unaligned format writes all columns of a row on one line, separated by the currently active field separator. Useful for creating output that other programs might read, like tab-separated or comma-separated format. But the field separator character isn't treated specially if it appears in a column's value β so CSV format may be better suited for that kind of thing. π
csv format writes column values separated by commas, applying the quoting rules described in RFC 4180. This output is compatible with the CSV format of the server's COPY command. A header line with column names is generated unless the tuples_only parameter is on. Titles and footers are not printed. Each row is terminated by the system-dependent end-of-line character β typically a single newline (\n) on Unix-like systems, or a carriage return plus newline sequence (\r\n) on Microsoft Windows. Field separator characters other than a comma can be selected with \pset csv_fieldsep. π
wrapped format is like aligned but it wraps wide data values across lines so the output fits in the target column width. The target width is determined as described under the columns option. Note that psql will not attempt to wrap column header titles; so wrapped format behaves the same as aligned if the total width needed for the column headers exceeds the target. π
The asciidoc, html, latex, latex-longtable, and troff-ms formats put out tables intended to be included in documents using the respective mark-up language. They are not complete documents! Might not matter for HTML, but in LaTeX you must have a complete document wrapper. The latex format uses LaTeX's tabular environment. The latex-longtable format requires the LaTeX longtable and booktabs packages. π
linestyleβ sets the border line drawing style to one ofascii,old-ascii, orunicode. Unique abbreviations are allowed. (Which means one letter is enough, bestie.) Default setting isascii. This option only affects thealignedandwrappedoutput formats. βοΈ
ascii style uses plain ASCII characters. Newlines in data are shown using a + symbol in the right-hand margin. When the wrapped format wraps data from one line to the next without a newline character, a dot (.) is shown in the right-hand margin of the first line, and again in the left-hand margin of the following line. π
old-ascii style uses plain ASCII characters, using the formatting style used in PostgreSQL 8.4 and earlier. Newlines in data are shown using a : symbol in place of the left-hand column separator. When the data is wrapped from one line to the next without a newline character, a ; symbol is used in place of the left-hand column separator. π°οΈ
unicode style uses Unicode box-drawing characters. Newlines in data are shown using a carriage return symbol in the right-hand margin. When the data is wrapped from one line to the next without a newline character, an ellipsis symbol is shown in the right-hand margin of the first line, and again in the left-hand margin of the following line. π
When the border setting is greater than zero, the linestyle option also determines the characters the border lines are drawn with. Plain ASCII characters work everywhere, but Unicode characters look nicer on displays that recognize them. π
nullβ sets the string to be printed in place of a null value. The default is to print nothing, which can easily be mistaken for an empty string. For example, you might prefer\pset null '(null)'. π«₯numericlocaleβ if you give a value it must be eitheronoroff, which enables or disables display of a locale-specific character to separate groups of digits to the left of the decimal marker. If value is omitted the command toggles between regular and locale-specific numeric output. π’pagerβ controls use of a pager program for query andpsqlhelp output. If the environment variablePSQL_PAGERorPAGERis set, output gets piped to the specified program. Otherwise a platform-dependent default program (such asmore) is used. π
When the pager option is off, the pager program isn't used. When the pager option is on, the pager is used when appropriate β i.e. when the output goes to a terminal and won't fit on the screen. The pager option can also be set to always, which causes the pager to be used for all terminal output regardless of whether it fits on screen. \pset pager without a value toggles pager use on and off. π
pager_min_linesβ ifpager_min_linesis set to a number greater than the page height, the pager program won't be called unless there are at least this many lines of output to show. Default setting is0. πrecordsepβ specifies the record (line) separator used inunalignedoutput format. Default is a newline character. π―recordsep_zeroβ sets the record separator used inunalignedoutput format to a zero byte. π«§tableattr(orT) β in HTML format, this specifies attributes to be placed inside thetabletag. Could becellpaddingorbgcolor, for example. Note that you probably don't want to specifyborderhere, since that's already taken care of by\pset border. If no value is given, the table attributes are unset. π¨
latex-longtablecolumnsβ ngl this one only matters if you're in latex-longtable format: it sets the proportional width of each column that's holding left-aligned data. You pass it as a whitespace-separated list of values, like'0.2 0.2 0.6'. Any output columns you didn't specify just inherit the last value you gave it. slay πtitle(orC) β sets the table title for every table printed after this. it's giving "descriptive tag era" β¨. If you give no value, the title gets unset.tuples_only(ort) β if you hand it a value it has to be eitheronoroff, which enables or disables tuples-only mode. If you omit the value, the command toggles between regular and tuples-only output. Regular output includes all the extra stuff β column headers, titles, various footers π. In tuples-only mode, only the actual table data shows up. literally just the data, bestie.unicode_border_linestyleβ sets the border drawing style for the unicode line style, to one ofsingleordouble.unicode_column_linestyleβ sets the column drawing style for the unicode line style, to one ofsingleordouble.unicode_header_linestyleβ sets the header drawing style for the unicode line style, to one ofsingleordouble.
Illustrations of how these different formats look can be seen in Examples, below. go look, they're cute π¦
Tip π‘ β there are various shortcut commands for\pset. see\a,\C,\f,\H,\t,\T, and\x.
\qor\quitβ quits thepsqlprogram. π In a script file, though, only execution of that script is terminated. so you can't rage-quit the whole thing from inside a script, sorry bestie.\qechotext [ ... ] β this command is identical to\echoexcept the output gets written to the query output channel, as set by\o. fancy β¨\ror\resetβ resets (clears) the query buffer. fresh start energy π§\restrictrestrict_key β enter "restricted" mode with the provided key π. In this mode, the only allowed meta-command is\unrestrict, to exit restricted mode. The key may contain only alphanumeric characters.
This command is primarily intended for use in plain-text dumps generated by pg_dump, pg_dumpall, and pg_restore, but it may be useful elsewhere.
\s[ filename ] β printpsql's command line history to filename. If filename is omitted, the history is written to the standard output (using the pager if appropriate). β οΈ heads up: this command is not available ifpsqlwas built without Readline support. no readline, no history bestie π\set[ name [ value [ ... ] ] ] β sets thepsqlvariable name to value, or, if you give more than one value, to the concatenation of all of them. If only one argument is given, the variable is set to an empty-string value. To unset a variable, use the\unsetcommand.
\set with no arguments at all displays the names and values of all currently-set psql variables. the full tour π
Valid variable names can contain letters, digits, and underscores. See Variables below for details. Variable names are case-sensitive β yes, really, watch the caps π₯
Certain variables are special, in that they control psql's behavior or are automatically set to reflect connection state. These variables are documented in Variables, below.
Note π β this command is unrelated to the SQL command SET. different thing entirely, don't @ me.
\setenvname [ value ] β sets the environment variable name to value, or, if the value isn't supplied, unsets the environment variable. Example:
testdb=> \setenv PAGER less
testdb=> \setenv LESS -imx4F
\sf[+]function_description β fetches and shows the definition of the named function or procedure, in the form of aCREATE OR REPLACE FUNCTIONorCREATE OR REPLACE PROCEDUREcommand π. The definition is printed to the current query output channel, as set by\o.
The target function can be specified by name alone, or by name and arguments, for example foo(integer, text). The argument types must be given if there is more than one function of the same name. iykyk π
If + is appended to the command name, then the output lines are numbered, with the first line of the function body being line 1.
Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \sf, and neither variable interpolation nor backquote expansion are performed in the arguments. nope, none, zero β
\sv[+]view_name β fetches and shows the definition of the named view, in the form of aCREATE OR REPLACE VIEWcommand. The definition is printed to the current query output channel, as set by\o.
If + is appended to the command name, then the output lines are numbered from 1.
Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \sv, and neither variable interpolation nor backquote expansion are performed in the arguments.
\tβ toggles the display of output column name headings and row count footer β¨. This command is equivalent to\pset tuples_onlyand is provided for convenience.\Ttable_options β specifies attributes to be placed within thetabletag in HTML output format. This command is equivalent to\pset tableattrtable_options.\timing[on|off] β with a parameter, turns displaying of how long each SQL statement takes on or off. Without a parameter, toggles the display between on and off. The display is in milliseconds β±οΈ; intervals longer than 1 second are also shown in minutes:seconds format, with hours and days fields added if needed. she really did the math π\unrestrictrestrict_key β exit "restricted" mode (i.e., where all other meta-commands are blocked), provided the specified key matches the one given to\restrictwhen restricted mode was entered π.
This command is primarily intended for use in plain-text dumps generated by pg_dump, pg_dumpall, and pg_restore, but it may be useful elsewhere.
Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument of \unrestrict, and neither variable interpolation nor backquote expansion are performed.
\unsetname β unsets (deletes) thepsqlvariable name.
Most variables that control psql's behavior cannot be unset; instead, an \unset command is interpreted as setting them to their default values π. See Variables below.
\wor\writefilename\wor\write|command
Writes the current query buffer to the file filename or pipes it to the shell command command. If the current query buffer is empty, the most recently executed query is written instead π«Ά
If the argument begins with |, then the entire remainder of the line is taken to be the command to execute, and neither variable interpolation nor backquote expansion are performed in it. The rest of the line is simply passed literally to the shell.
\warntext [ ... ] β identical to\echoexcept the output is written topsql's standard error channel, rather than standard output π. loud mode.\watch[ seconds ] β repeatedly execute the current query buffer (as\gdoes) until interrupted or the query fails. Wait the specified number of seconds (default2) between executions β³. Each query result is displayed with a header that includes the\pset titlestring (if any), the time as of query start, and the delay interval.
If the current query buffer is empty, the most recently sent query is re-executed instead.
\x[on|off|auto] β sets or toggles expanded table formatting mode. As such it's equivalent to\pset expanded. the wide-table savior π¦\z[ pattern ] β lists tables, views and sequences with their associated access privileges. If a pattern is specified, only tables, views and sequences whose names match the pattern are listed.
This is an alias for \dp ("display privileges") π
\![ command ] β with no argument, escapes to a sub-shell;psqlresumes when the sub-shell exits. With an argument, executes the shell command command π
Unlike most other meta-commands, the entire remainder of the line is always taken to be the argument(s) of \!, and neither variable interpolation nor backquote expansion are performed in the arguments. The rest of the line is simply passed literally to the shell.
\?[ topic ] β shows help information. The optional topic parameter (defaulting tocommands) selects which part ofpsqlis explained:commandsdescribespsql's backslash commands;optionsdescribes the command-line options that can be passed topsql; andvariablesshows help aboutpsqlconfiguration variables π. built-in help bestie, use it.\;β okay so backslash-semicolon is not a meta-command the same way as the ones above π¨; rather, it simply causes a semicolon to be added to the query buffer without any further processing.
Normally, psql will dispatch an SQL command to the server as soon as it reaches the command-ending semicolon, even if more input remains on the current line. Thus for example entering
select 1; select 2; select 3;
will result in the three SQL commands being individually sent to the server, with each one's results being displayed before continuing to the next command π₯. However, a semicolon entered as \; will not trigger command processing, so that the command before it and the one after are effectively combined and sent to the server in one request. So for example
select 1\; select 2\; select 3;
results in sending the three SQL commands to the server in a single request, when the non-backslashed semicolon is reached π
. The server executes such a request as a single transaction, unless there are explicit BEGIN/COMMIT commands included in the string to divide it into multiple transactions. (See Section 53.2.2.1 for more details about how the server handles multi-query strings.) psql prints only the last query result it receives for each request; in this example, although all three SELECTs are indeed executed, psql only prints the 3. not a bug, it's the vibe check β¨
π Patterns
okay so patterns β this next bit is literally all about them, bestie π
Okay so the various \d commands take a pattern parameter β that's how you tell them which object name(s) you wanna see π
. In the simplest case, the pattern is literally just the exact name of the object. The characters in a pattern normally get folded to lower case, just like in SQL names β so \dt FOO will show you the table named foo. And just like SQL names, wrapping a pattern in double quotes stops that lower-case folding. If you actually need a double quote character inside a pattern, write it as a pair of double quotes inside a double-quoted sequence β yep, same rules as SQL quoted identifiers. For example, \dt "FOO""BAR" shows the table named FOO"BAR (not foo"bar). And unlike normal SQL-name rules, you can double-quote just part of a pattern β \dt FOO"FOO"BAR shows the table named fooFOObar.
If you leave the pattern parameter out completely, the \d commands show every object that's visible in the current schema search path β that's equivalent to using * as the pattern. (Quick visibility check: an object is visible when its containing schema is in the search path and no object of the same kind and name shows up earlier in the search path. Same thing as saying the object can be referenced by name without explicitly qualifying the schema.) Wanna see every object in the database regardless of visibility? Use *.* as the pattern. Periodt.
Inside a pattern, * matches any sequence of characters (including zero characters), and ? matches any single character β it's giving Unix shell file name patterns. So \dt int* shows tables whose names begin with int. But inside double quotes, * and ? lose their special meanings and are just matched literally. No globbing, bestie.
A relation pattern that contains a dot (.) is interpreted as a schema name pattern followed by an object name pattern. Example: \dt foo*.*bar* displays all tables whose table name includes bar and that are in schemas whose schema name starts with foo. When no dot appears, the pattern matches only objects that are visible in the current schema search path. Again, a dot inside double quotes loses its special meaning and is matched literally. A relation pattern that contains two dots (.) is interpreted as a database name followed by a schema name pattern followed by an object name pattern. The database name portion is not treated as a pattern and must match the name of the currently connected database β otherwise an error will be raised. So don't try to be cute with the database part, mmmkay? π
A schema pattern that contains a dot (.) is interpreted as a database name followed by a schema name pattern. For example, \dn mydb.*foo* displays all schemas whose schema name includes foo. The database name portion is not treated as a pattern and must match the name of the currently connected database, else an error will be raised. Same energy, different command.
Advanced users can use regular-expression notations like character classes β [0-9] to match any digit, for example. All regular expression special characters work as specified in Section 9.7.3, except for these little exceptions: . is taken as a separator like we said above; * is translated to the regular-expression notation .*; ? is translated to .; and $ is matched literally. Need to emulate these pattern characters? You can write ? for ., (R+|) for R*, or (R|) for R?. The $ isn't needed as a regular-expression character because the pattern has to match the whole name β unlike the usual interpretation of regular expressions β in other words, $ is automatically appended to your pattern. Write * at the beginning and/or end if you don't want the pattern to be anchored. Note: inside double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).
π Advanced Features π
π Variables π
psql gives you variable substitution features similar to common Unix command shells β think name/value pairs, where the value can be any string of any length. The name has to consist of letters (including non-Latin letters), digits, and underscores. Slay.
To set a variable, use the psql meta-command \set. For example:
testdb=> \set foo bar
That sets the variable foo to the value bar. To retrieve the content of a variable, put a colon in front of the name, like:
testdb=> \echo :foo
bar
This works in both regular SQL commands and meta-commands; there's more detail in SQL Interpolation, below.
If you call \set without a second argument, the variable gets set to an empty-string value. To unset (i.e., delete) a variable, use the command \unset. To show the values of all variables, call \set without any argument.
Note π‘ The arguments of\setare subject to the same substitution rules as with other commands. So you can construct interesting references such as\set :foo 'something'and get βsoft linksβ or βvariable variablesβ of Perl or PHP fame, respectively. Unfortunately (or fortunately?), there's no way to do anything useful with these constructs. On the other hand,\set bar :foois a perfectly valid way to copy a variable.
A number of these variables are treated specially by psql. They represent certain option settings that can be changed at run time by altering the value of the variable, or in some cases represent changeable state of psql. By convention, all specially treated variables' names consist of all upper-case ASCII letters (and possibly digits and underscores). To ensure maximum compatibility in the future, avoid using such variable names for your own purposes.
Variables that control psql's behavior generally cannot be unset or set to invalid values. An \unset command is allowed but is interpreted as setting the variable to its default value. A \set command without a second argument is interpreted as setting the variable to on, for control variables that accept that value, and is rejected for others. Also, control variables that accept the values on and off will also accept other common spellings of Boolean values, such as true and false.
The specially treated variables are:
AUTOCOMMITβ Whenon(the default), each SQL command is automatically committed upon successful completion. To postpone commit in this mode, you must enter aBEGINorSTART TRANSACTIONSQL command. Whenoffor unset, SQL commands are not committed until you explicitly issueCOMMITorEND. The autocommit-off mode works by issuing an implicitBEGINfor you, just before any command that is not already in a transaction block and is not itself aBEGINor other transaction-control command, nor a command that cannot be executed inside a transaction block (such asVACUUM).
Note π In autocommit-off mode, you must explicitly abandon any failed transaction by enteringABORTorROLLBACK. Also keep in mind that if you exit the session without committing, your work will be lost.
Note β¨ The autocommit-on mode is PostgreSQL's traditional behavior, but autocommit-off is closer to the SQL spec. If you prefer autocommit-off, you might wish to set it in the system-widepsqlrcfile or your~/.psqlrcfile.
COMP_KEYWORD_CASEβ Determines which letter case to use when completing an SQL key word. If set tolowerorupper, the completed word will be in lower or upper case, respectively. If set topreserve-lowerorpreserve-upper(the default), the completed word will be in the case of the word already entered, but words being completed without anything entered will be in lower or upper case, respectively.DBNAMEβ The name of the database you are currently connected to. This is set every time you connect to a database (including program start-up), but can be changed or unset.ECHOβ If set toall, all nonempty input lines are printed to standard output as they are read. (This does not apply to lines read interactively.) To select this behavior on program start-up, use the switch-a. If set toqueries, psql prints each query to standard output as it is sent to the server. The switch to select this behavior is-e. If set toerrors, then only failed queries are displayed on standard error output. The switch for this behavior is-b. If set tonone(the default), then no queries are displayed.ECHO_HIDDENβ When this variable is set toonand a backslash command queries the database, the query is first shown. This feature helps you to study PostgreSQL internals and provide similar functionality in your own programs. (To select this behavior on program start-up, use the switch-E.) If you set this variable to the valuenoexec, the queries are just shown but are not actually sent to the server and executed. The default value isoff.ENCODINGβ The current client character set encoding. This is set every time you connect to a database (including program start-up), and when you change the encoding with\encoding, but it can be changed or unset.ERRORβtrueif the last SQL query failed,falseif it succeeded. See alsoSQLSTATE.FETCH_COUNTβ If this variable is set to an integer value greater than zero, the results ofSELECTqueries are fetched and displayed in groups of that many rows, rather than the default behavior of collecting the entire result set before display. Therefore only a limited amount of memory is used, regardless of the size of the result set. Settings of100to1000are commonly used when enabling this feature. Keep in mind that when using this feature, a query might fail after having already displayed some rows.
Tip π‘ β you can use any output format with this feature, but ngl the default aligned format tends to look bad, because each group of FETCH_COUNT rows gets formatted separately, so the column widths end up varying across the row groups π¬ The other output formats work better, fr.
HIDE_TABLEAMβ set this totrueand a table's access method deets aren't displayed anymore. It's mainly useful for regression tests, so lowkey a dev-only vibe π§ͺHIDE_TOAST_COMPRESSIONβ set this one totrueand the column compression method details get hidden. Again, mainly useful for regression tests π«ΆHISTCONTROLβ the history gatekeeper β¨ Set it toignorespaceand any line starting with a space does not get entered into the history list (secret commands, iykyk π). Set it toignoredupsand lines matching the previous history line don't get entered either. Set it toignorebothand it combines the two, iconic. And if it'snone(the default), every single line you read in interactive mode is saved to the history list, no filter, no cap π
Note π This feature was shamelessly plagiarized from Bash.
HISTFILEβ the file name used to store the history list π If it's unset, the file name is taken from thePSQL_HISTORYenvironment variable. If that's not set either, the default is~/.psql_history, or%APPDATA%\postgresql\psql_historyon Windows. For example, putting:
\set HISTFILE ~/.psql_history-:DBNAME
in ~/.psqlrc will cause psql to maintain a separate history for each database. bestie that's so clean π«§
Note π This feature was shamelessly plagiarized from Bash.
HISTSIZEβ the max number of commands to store in the command history (default500). Set it to a negative value and no limit is applied at all β unlimited history era, no cap fr π₯
Note π This feature was shamelessly plagiarized from Bash.
HOSTβ the database server host you're currently connected to π This gets set every time you connect to a database (including program start-up), but you can change it or unset it.IGNOREEOFβ if set to1or less, sending an EOF character (usually Control+D) to an interactive session of psql will terminate the application, bye π If it's set to a larger numeric value, that many consecutive EOF characters must be typed to make an interactive session terminate. If the variable is set to a non-numeric value, it's interpreted as10. The default is0.
Note π This feature was shamelessly plagiarized from Bash.
LASTOIDβ the value of the last affected OID, as returned from anINSERTor\lo_importcommand. Heads up: this variable is only guaranteed to be valid until after the result of the next SQL command has been displayed β³ And btw, PostgreSQL servers since version 12 do not support OID system columns anymore, soLASTOIDwill always be0followingINSERTwhen targeting such servers πLAST_ERROR_MESSAGE,LAST_ERROR_SQLSTATEβ the primary error message and associated SQLSTATE code for the most recent failed query in the current psql session π or an empty string and00000if no error has occurred in the current session. (no errors? couldn't be me β¨)ON_ERROR_ROLLBACKβ set it toonand if a statement in a transaction block generates an error, the error is ignored and the transaction just continues, unbothered π Set it tointeractiveand those errors are only ignored in interactive sessions, and not when reading script files. Set it tooff(the default) and a statement in a transaction block that generates an error aborts the entire transaction β everything goes down π The error rollback mode works by issuing an implicitSAVEPOINTfor you, just before each command that's in a transaction block, and then rolling back to the savepoint if the command fails. very "undo my mistake" of it πON_ERROR_STOPβ by default, command processing continues after an error. When this variable is set toon, processing will instead stop immediately β In interactive mode, psql will return to the command prompt; otherwise, psql will exit, returning error code3to distinguish this case from fatal error conditions, which are reported using error code1. In either case, any currently running scripts (the top-level script, if any, and any other scripts which it may have in invoked) will be terminated immediately. If the top-level command string contained multiple SQL commands, processing will stop with the current command.PORTβ the database server port you're currently connected to π This is set every time you connect to a database (including program start-up), but can be changed or unset.PROMPT1,PROMPT2,PROMPT3β these specify what the prompts psql issues should look like π See Prompting below.QUIETβ setting this variable toonis equivalent to the command line option-q. It's probably not too useful in interactive mode, ngl π€·ROW_COUNTβ the number of rows returned or affected by the last SQL query, or0if the query failed or did not report a row count. counting the receipts fr π§ΎSERVER_VERSION_NAME,SERVER_VERSION_NUMβ the server's version number as a string, for example9.6.2,10.1or11beta1, and in numeric form, for example90602or100001. These are set every time you connect to a database (including program start-up), but can be changed or unset.SHOW_CONTEXTβ this variable can be set to the valuesnever,errors, oralwaysto control whetherCONTEXTfields are displayed in messages from the server π The default iserrors(meaning that context will be shown in error messages, but not in notice or warning messages). This setting has no effect whenVERBOSITYis set toterseorsqlstate. (See also\errverbose, for use when you want a verbose version of the error you just got.) π«ΆSINGLELINEβ setting this variable toonis equivalent to the command line option-S.SINGLESTEPβ setting this variable toonis equivalent to the command line option-s.SQLSTATEβ the error code (see Appendix A) associated with the last SQL query's failure, or00000if it succeeded β¨USERβ the database user you're currently connected as π«΅ This is set every time you connect to a database (including program start-up), but can be changed or unset.VERBOSITYβ this variable can be set to the valuesdefault,verbose,terse, orsqlstateto control the verbosity of error reports π£οΈ (See also\errverbose, for use when you want a verbose version of the error you just got.)VERSION,VERSION_NAME,VERSION_NUMβ these variables are set at program start-up to reflect psql's version, respectively as a verbose string, a short string (e.g.,9.6.2,10.1, or11beta1), and a number (e.g.,90602or100001). They can be changed or unset β
β¨ SQL Interpolation β¨
Okay so this is like, a key feature of psql variables β you can substitute ("interpolate") them into regular SQL statements, as well as the arguments of meta-commands π¦ And psql also provides facilities for ensuring that variable values used as SQL literals and identifiers are properly quoted, which is the safety net you didn't know you needed π«Ά
The syntax for interpolating a value without any quoting is to prepend the variable name with a colon (:). For example,
testdb=> \set foo 'my_table'
testdb=> SELECT * FROM :foo;
would query the table my_table. But bestie, note that this may be unsafe: the value of the variable is copied literally, so it can contain unbalanced quotes, or even backslash commands π¬ You must make sure that it makes sense where you put it. it's giving "trust me bro" energy, don't do that.
When a value is to be used as an SQL literal or identifier, it's safest to arrange for it to be quoted π To quote the value of a variable as an SQL literal, write a colon followed by the variable name in single quotes. To quote the value as an SQL identifier, write a colon followed by the variable name in double quotes. These constructs deal correctly with quotes and other special characters embedded within the variable value β the way that just works β¨ The previous example would be more safely written this way:
testdb=> \set foo 'my_table'
testdb=> SELECT * FROM :"foo";
Variable interpolation will not be performed within quoted SQL literals and identifiers π
ββοΈ Therefore, a construction such as ':foo' doesn't work to produce a quoted literal from a variable's value (and it would be unsafe if it did work, since it wouldn't correctly handle quotes embedded in the value). so don't try it, it's not that girl.
One example use of this mechanism is to copy the contents of a file into a table column π First load the file into a variable and then interpolate the variable's value as a quoted string:
testdb=> \set content `cat my_file.txt`
testdb=> INSERT INTO my_table VALUES (:'content');
(Note that this still won't work if my_file.txt contains NUL bytes. psql does not support embedded NUL bytes in variable values. rude, but okay π)
Since colons can legally appear in SQL commands, an apparent attempt at interpolation (that is, :name, :'name', or :"name") is not replaced unless the named variable is currently set π― In any case, you can escape a colon with a backslash to protect it from substitution.
The :{?name} special syntax returns TRUE or FALSE depending on whether the variable exists or not, and is thus always substituted, unless the colon is backslash-escaped. lowkey such a useful lil guy π
The colon syntax for variables is standard SQL for embedded query languages, such as ECPG. The colon syntaxes for array slices and type casts are PostgreSQL extensions, which can sometimes conflict with the standard usage π The colon-quote syntax for escaping a variable's value as an SQL literal or identifier is a psql extension.
πΈ Prompting πΈ
The prompts psql throws at you are fully customizable, bestie π
β the three variables PROMPT1, PROMPT2, and PROMPT3 hold strings plus special escape sequences that define how your prompt looks. Prompt 1 is the normal one you see when psql wants a new command. Prompt 2 shows up when it's expecting more input mid-command β like when you forgot the semicolon or left a quote hanging π. Prompt 3 is the one for when you're running an SQL COPY FROM STDIN and need to type a row value right there on the terminal.
The value of whichever prompt variable you picked gets printed literally, except when a percent sign (%) shows up β then, depending on the next character, something else gets substituted in. Here's the full menu of substitutions:
%Mβ the full host name (domain name included) of the database server, or[local]if you're connecting over a Unix domain socket, or[local:/dir/name]if that Unix domain socket isn't sitting in the compiled-in default location.%mβ the database server's host name, chopped off at the first dot, or[local]if it's a Unix domain socket connection.%>β the port number the database server is listening on.%nβ the database session user name. (Heads up: this value's expansion can change mid-session if you runSET SESSION AUTHORIZATION.)%/β the name of the current database.%~β same as%/, except the output is~(tilde) when the database is your default database. Cute.%#β a#if the session user is a database superuser, otherwise a>. (Again, this can shift mid-session thanks toSET SESSION AUTHORIZATION.)%pβ the process ID of the backend you're currently connected to.%Rβ in prompt 1 it's normally=, but@if the session is in an inactive branch of a conditional block, or^if in single-line mode, or!if the session is disconnected from the database (which can happen if\connectfails). In prompt 2,%Rgets swapped for a character depending on whypsqlwants more input:-if the command simply wasn't terminated yet, but*if there's an unfinished/* ... */comment, a single quote if there's an unfinished quoted string, a double quote if there's an unfinished quoted identifier, a dollar sign if there's an unfinished dollar-quoted string, or(if there's an unmatched left parenthesis. In prompt 3,%Rdoesn't produce anything at all.%xβ transaction status: an empty string when you're not in a transaction block, or*when in a transaction block, or!when in a failed transaction block, or?when the transaction state is indeterminate (for example, because there's no connection).%lβ the line number inside the current statement, starting from 1.%digitsβ the character with the indicated octal code gets substituted in.%:name:β the value of thepsqlvariable name. Peep the Variables section above for the deets.%command`` β the output of command, similar to ordinary "back-tick" substitution.%[ ... %]β prompts can contain terminal control characters that, like, change the color, background, or style of the prompt text, or change the terminal window title. For Readline's line editing features to work properly, these non-printing control characters must be marked as invisible by wrapping them in%[and%]. You can have multiple pairs of these inside one prompt. For example:
testdb=> \set PROMPT1 '%[%033[1;33;40m%]%n@%/%R%[%033[0m%]%# '
gives you a boldfaced (1;) yellow-on-black (33;40) prompt on VT100-compatible, color-capable terminals β¨.
%wβ whitespace of the same width as the most recent output ofPROMPT1. Use this as aPROMPT2setting so multi-line statements line up with the first line, but with no visible secondary prompt. Chef's kiss π.
To stick an actual percent sign into your prompt, write %%. The default prompts are '/%/%R%x%# ' for prompts 1 and 2, and '>> ' for prompt 3.
Note β this feature was shamelessly plagiarized from tcsh π.
π¦ Command-Line Editing
psql supports the Readline library for convenient line editing and retrieval, periodt. Your command history is automatically saved when psql exits and reloaded when it starts up. Tab-completion is supported too, though the completion logic makes no claim to being an SQL parser β and the queries tab-completion generates can also interfere with other SQL commands, e.g. SET TRANSACTION ISOLATION LEVEL. If for some reason you don't vibe with tab completion, you can turn it off by putting this in a file named .inputrc in your home directory:
$if psql
set disable-completion on
$endif
(This is not a psql thing, it's a Readline feature β read its documentation for further details.)
π ENVIRONMENT
COLUMNSβ if\pset columnsis zero, this controls the width for the wrapped format, and the width used to determine whether wide output needs the pager or should be switched to the vertical format in expanded auto mode.PGDATABASE,PGHOST,PGPORT,PGUSERβ default connection parameters (see Section 34.15).PG_COLORβ specifies whether to use color in diagnostic messages. Possible values arealways,auto, andnever.PSQL_EDITOR,EDITOR,VISUALβ the editor used by the\e,\ef, and\evcommands. These variables are examined in the order listed; the first one that's set is the one that gets used. If none of them is set, the default is to usevion Unix systems ornotepad.exeon Windows systems.PSQL_EDITOR_LINENUMBER_ARGβ when\e,\ef, or\evis used with a line number argument, this variable specifies the command-line argument used to pass the starting line number to your editor. For editors like Emacs or vi, this is a plus sign. Include a trailing space in the variable's value if there needs to be a space between the option name and the line number. Examples:
PSQL_EDITOR_LINENUMBER_ARG='+'
PSQL_EDITOR_LINENUMBER_ARG='--line '
The default is + on Unix systems (corresponding to the default editor vi, and useful for many other common editors); but there is no default on Windows systems.
PSQL_HISTORYβ alternative location for the command history file. Tilde (~) expansion is performed.PSQL_PAGER,PAGERβ if a query's results don't fit on the screen, they get piped through this command. Typical values aremoreorless. You can disable the pager by settingPSQL_PAGERorPAGERto an empty string, or by adjusting the pager-related options of the\psetcommand. These variables are examined in the order listed; the first one that's set is the one that gets used. If none of them is set, the default is to usemoreon most platforms, butlesson Cygwin.PSQLRCβ alternative location of the user's.psqlrcfile. Tilde (~) expansion is performed.SHELLβ the command executed by the\!command.TMPDIRβ directory for storing temporary files. The default is/tmp.
This utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 34.15).
π FILES
psqlrc and ~/.psqlrc
Unless it's passed an -X option, psql attempts to read and execute commands from the system-wide startup file (psqlrc) and then the user's personal startup file (~/.psqlrc), after connecting to the database but before accepting normal commands π. These files are your moment to set up the client and/or the server to taste β typically with \set and SET commands.
The system-wide startup file is named psqlrc and is sought in the installation's "system configuration" directory, which is most reliably identified by running pg_config --sysconfdir. By default this directory will be ../etc/ relative to the directory containing the PostgreSQL executables. The name of this directory can be set explicitly via the PGSYSCONFDIR environment variable.
The user's personal startup file is named .psqlrc and is sought in the invoking user's home directory. On Windows, which lacks such a concept, the personal startup file is named %APPDATA%\postgresql\psqlrc.conf. The location of the user's startup file can be set explicitly via the PSQLRC environment variable.
Both the system-wide startup file and the user's personal startup file can be made psql-version-specific by appending a dash and the PostgreSQL major or minor release number to the file name, for example ~/.psqlrc-9.2 or ~/.psqlrc-9.2.5. The most specific version-matching file will be read in preference to a non-version-specific file. Slay π¦.
.psql_history
The command-line history is stored in the file ~/.psql_history, or %APPDATA%\postgresql\psql_history on Windows.
The location of the history file can be set explicitly via the HISTFILE psql variable or the PSQL_HISTORY environment variable.
β NOTES
psqlworks best with servers of the same or an older major version. Backslash commands are particularly likely to fail if the server is a newer version thanpsqlitself π. However, backslash commands of the\dfamily should work with servers of versions back to 7.4, though not necessarily with servers newer thanpsqlitself. The general functionality of running SQL commands and displaying query results should also work with servers of a newer major version, but this cannot be guaranteed in all cases.
If you want to use psql to connect to several servers of different major versions, it's recommended that you use the newest version of psql. Alternatively, you can keep around a copy of psql from each major version and be sure to use the version that matches the respective server. But in practice, this additional complication should not be necessary.
- Before PostgreSQL 9.6, the
-coption implied-X(--no-psqlrc); this is no longer the case. - Before PostgreSQL 8.4,
psqlallowed the first argument of a single-letter backslash command to start directly after the command, without intervening whitespace. Now, some whitespace is required.
πͺ NOTES FOR WINDOWS USERS πͺ
okay bestie, if you're on Windows, listen up because this part is specifically for you π
psql is built as a "console application". And since the Windows console windows use a different encoding than the rest of the system, you have to take special care when using 8-bit characters inside psql. no cap, this matters. If psql detects a problematic console code page, it will warn you at startup β consider that your little heads-up text, bestie π
To change the console code page, two things are necessary:
- Set the code page by entering
cmd.exe /c chcp 1252. (1252 is a code page that is appropriate for German; replace it with your value.) If you are using Cygwin, you can put this command in/etc/profile. - Set the console font to
Lucida Console, because the raster font does not work with the ANSI code page. yes, really, the raster font is not it π
π EXAMPLES π
β¨ spreading a command over several lines β¨
The first example shows how to spread a command over several lines of input. Notice the changing prompt β it's giving main character energy, the prompt literally morphs as you go π¦
testdb=> CREATE TABLE my_table (
testdb(> first integer not null default 0,
testdb(> second text)
testdb-> ;
CREATE TABLE
π looking at the table definition again π
Now look at the table definition again:
testdb=> \d my_table
Table "public.my_table"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
first | integer | | not null | 0
second | text | | |
π changing the prompt to something more interesting π
Now we change the prompt to something more interesting:
testdb=> \set PROMPT1 '%n@%m %~%R%# '
peter@localhost testdb=>
π filling the table and peeking at it π
Let's assume you have filled the table with data and want to take a look at it:
peter@localhost testdb=> SELECT * FROM my_table;
first | second
-------+--------
1 | one
2 | two
3 | three
4 | four
(4 rows)
π
displaying tables in different ways with \pset π
You can display tables in different ways by using the \pset command. watch this glow-up:
peter@localhost testdb=> \pset border 2
Border style is 2.
peter@localhost testdb=> SELECT * FROM my_table;
+-------+--------+
| first | second |
+-------+--------+
| 1 | one |
| 2 | two |
| 3 | three |
| 4 | four |
+-------+--------+
(4 rows)
peter@localhost testdb=> \pset border 0
Border style is 0.
peter@localhost testdb=> SELECT * FROM my_table;
first second
----- ------
1 one
2 two
3 three
4 four
(4 rows)
peter@localhost testdb=> \pset border 1
Border style is 1.
peter@localhost testdb=> \pset format csv
Output format is csv.
peter@localhost testdb=> \pset tuples_only
Tuples only is on.
peter@localhost testdb=> SELECT second, first FROM my_table;
one,1
two,2
three,3
four,4
peter@localhost testdb=> \pset format unaligned
Output format is unaligned.
peter@localhost testdb=> \pset fieldsep '\t'
Field separator is " ".
peter@localhost testdb=> SELECT second, first FROM my_table;
one 1
two 2
three 3
four 4
β‘ or like, use the short commands β‘
Alternatively, use the short commands β lowkey easier, highkey iconic:
peter@localhost testdb=> \a \t \x
Output format is aligned.
Tuples only is off.
Expanded display is on.
peter@localhost testdb=> SELECT * FROM my_table;
-[ RECORD 1 ]-
first | 1
second | one
-[ RECORD 2 ]-
first | 2
second | two
-[ RECORD 3 ]-
first | 3
second | three
-[ RECORD 4 ]-
first | 4
second | four
π«Ά output format for just ONE query, via \g π«Ά
Also, these output format options can be set for just one query by using \g. obsessed, honestly:
peter@localhost testdb=> SELECT * FROM my_table
peter@localhost testdb-> \g (format=aligned tuples_only=off expanded=on)
-[ RECORD 1 ]-
first | 1
second | one
-[ RECORD 2 ]-
first | 2
second | two
-[ RECORD 3 ]-
first | 3
second | three
-[ RECORD 4 ]-
first | 4
second | four
π§ finding functions with \df π§
Here is an example of using the \df command to find only functions with names matching int*pl and whose second argument is of type bigint:
testdb=> \df int*pl * bigint
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+---------+------------------+---------------------+------
pg_catalog | int28pl | bigint | smallint, bigint | func
pg_catalog | int48pl | bigint | integer, bigint | func
pg_catalog | int8pl | bigint | bigint, bigint | func
(3 rows)
π¦ crosstab vibes with \crosstabview π¦
When suitable, query results can be shown in a crosstab representation with the \crosstabview command:
testdb=> SELECT first, second, first > 2 AS gt2 FROM my_table;
first | second | gt2
-------+--------+-----
1 | one | f
2 | two | f
3 | three | t
4 | four | t
(4 rows)
testdb=> \crosstabview first second
first | one | two | three | four
-------+-----+-----+-------+------
1 | f | | |
2 | | f | |
3 | | | t |
4 | | | | t
(4 rows)
π the multiplication table, crosstab edition π
This second example shows a multiplication table with rows sorted in reverse numerical order and columns with an independent, ascending numerical order. it's giving math class but cute π
testdb=> SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as "AxB",
testdb(> row_number() over(order by t2.first) AS ord
testdb(> FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC
testdb(> \crosstabview "A" "B" "AxB" ord
A | 101 | 102 | 103 | 104
---+-----+-----+-----+-----
4 | 404 | 408 | 412 | 416
3 | 303 | 306 | 309 | 312
2 | 202 | 204 | 206 | 208
1 | 101 | 102 | 103 | 104
(4 rows)
and that's the whole page, bestie, we made it to the end ππ you now know psql better than most people know their own passwords (which, uh, is a low bar, but still). go forth and query, and may your prompts always be %n@%m %~%R%# πΈ
β¨ k bye, this was PostgreSQL 14.24, dated 2026, page PSQL(1) β slay β¨
π¦ where this page comes from
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms