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 are what makes psql interesting for administration or scripting. Meta-commands are more commonly 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 into an argument you must quote it with a single quote. To include a single quote into such an argument, precede it by a backslash. Anything contained in single quotes is furthermore subject to C-like substitutions for \n (new line), \t (tab), \digits, \0digits, and \0xdigits (the character with the given decimal, octal, or hexadecimal code).

If an unquoted argument begins with a colon (:), it is taken as a variable and the value of the variable is taken as the argument instead.

Arguments that are quoted in "backticks" (`) are taken as a command line that is passed to the shell. The output of the command (with a trailing newline removed) is taken as the argument value. The above escape sequences also apply in backticks.

Some commands take the name of an SQL identifier (such as a table name) as argument. These arguments follow the lower-case syntax rules of SQL regarding double quotes: an identifier without double quotes is made lower-case. For all other commands double quotes are not special and will become part of the argument.

Parsing for arguments stops when another unquoted backslash occurs. This is taken as the beginning of a new meta-command. The special sequence \\ (two backslashes) marks the end of arguments and continues parsing SQL queries, 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.

The following meta-commands are defined:

\a

If the current table output format is unaligned, switch to aligned. If it is not unaligned, set it to unaligned. This command is kept for backwards compatibility. See \pset for a general solution.

\cd [directory]

Change the current working directory to directory. Without argument, change to the current user's home directory.

Tip

To print your current working directory, use \!pwd.

\C [ title ]

Set the title of any tables being printed as the result of a query or unset any such title. This command is equivalent to \pset title title. (The name of this command derives from "caption", as it was previously only used to set the caption in an HTML table.)

\connect (or \c) [ dbname [ username ] ]

Establishes a connection to a new database and/or under a user name. The previous connection is closed. If dbname is - the current database name is assumed.

If username is omitted the current user name is assumed.

As a special rule, \connect without any arguments will connect to the default database as the default user (as you would have gotten by starting psql without any arguments).

If the connection attempt failed (wrong username, access denied, etc.), the previous connection will be kept if and only if psql is in interactive mode. When executing a non-interactive script, processing will immediately stop with the first error. 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.

\copy table [ with oids ] { from | to } filename | stdin | stdout [ using delimiters 'characters' ] [ with null as 'string' ]

Performs a frontend (client) copy. This runs an SQL COPY command. However, instead of the backend reading or writing the specified file and consequently requiring backend access and special user privilege (as well as being bound to the file system accessible by the backend), psql reads or writes the file and routes the data between the backend and the local file system.

The syntax of the command is similar to that of the SQL COPY command (see its description for the details). Note that, because of this, special parsing rules apply to the \copy command. In particular, the variable substitution rules and backslash escapes do not apply.

Tip

This operation is not as efficient as the SQL COPY command because all data must pass through the client/server IP or socket connection. For large amounts of data an SQL copy may be preferable.

Note

Note the difference in interpretation of stdin and stdout between frontend and backend copies: in a frontend copy these always refer to psql's input and output stream. On a backend copy stdin comes from wherever the COPY itself came from (for example, a script run with the -f option), and stdout refers to the query output stream (see \o meta-command below).

\copyright

Shows the copyright and distribution terms of PostgreSQL.

\d relation

Shows all columns of relation (which could be a table, view, index, or sequence), their types, and any special attributes such as NOT NULL or defaults, if any. If the relation is, in fact, a table, any defined indexes are also listed. If the relation is a view, the view definition is also shown.

The command form \d+ is identical, but any comments associated with the table columns are shown as well.

Note

If \d is called without any arguments, it is equivalent to \dtvs which will show a list of all tables, views, and sequences. This is purely a convenience measure.

\da [ pattern ]

Lists all available aggregate functions, together with the data type they operate on. If pattern (a regular expression) is specified, only matching aggregates are shown.

\dd [ object ]

Shows the descriptions of object (which can be a regular expression), or of all objects if no argument is given. ("Object" covers aggregates, functions, operators, types, relations (tables, views, indexes, sequences, large objects), rules, and triggers.) For example:
=> \dd version
      Object descriptions
  Name   |   What   |Description
---------+----------+---------------------------
 version | function | PostgreSQL version string
(1 row)

Descriptions for objects can be generated with the COMMENT ON SQL command.

Note

PostgreSQL stores the object descriptions in the pg_description system table.

\df [ pattern ]

Lists available functions, together with their argument and return types. If pattern (a regular expression) is specified, only matching functions are shown. If the form \df+ is used, additional information about each function, including language and description, is shown.

\distvS [ pattern ]

This is not the actual command name: the letters i, s, t, v, S stand for index, sequence, table, view, and system table, respectively. You can specify any or all of them in any order to obtain a listing of them, together with who the owner is.

If pattern is specified, it is a regular expression that restricts the listing to those objects whose name matches. If one appends a "+" to the command name, each object is listed with its associated description, if any.

\dl

This is an alias for \lo_list, which shows a list of large objects.

\do [ name ]

Lists available operators with their operand and return types. If name is specified, only operators with that name will be shown.

\dp [ pattern ]

This is an alias for \z which was included for its greater mnemonic value ("display permissions").

\dT [ pattern ]

Lists all data types or only those that match pattern. The command form \dT+ shows extra information.

\du [ pattern ]

Lists all configured users or only those that match pattern.

\edit (or \e) [ filename ]

If filename is specified, the file is edited; after the editor exits, its content is copied back to the query buffer. If no argument is given, the current query buffer is copied to a temporary file which is then edited in the same fashion.

The new query buffer is then re-parsed according to the normal rules of psql, where the whole buffer is treated as a single line. (Thus you cannot make scripts this way. Use \i for that.) This also means that if the query contains a semicolon, it is immediately executed. In other cases it will merely wait in the query buffer.

Tip

psql searches the environment variables PSQL_EDITOR, EDITOR, and VISUAL (in that order) for an editor to use. If all of them are unset, /bin/vi is run.

\echo text [ ... ]

Prints the arguments to the standard output, separated by one space and followed by a newline. This can be useful to intersperse information in the output of scripts. For example:
=> \echo `date`
Tue Oct 26 21:40:57 CEST 1999
If the first argument is an unquoted -n, the trailing newline is not written.

Tip

If you use the \o command to redirect your query output, you may want to use \qecho instead of this command.

\encoding [ encoding ]

Sets the client encoding, if you are using multibyte encodings. Without an argument, this command shows the current encoding.

\f [ string ]

Sets the field separator for unaligned query output. The default is pipe (|). See also \pset for a generic way of setting output options.

\g [ { filename | |command } ]

Sends the current query input buffer to the backend and optionally saves the output in filename or pipes the output into a separate Linux shell to execute command. A bare \g is virtually equivalent to a semicolon. A \g with argument is a "one-shot" alternative to the \o command.

\help (or \h) [ command ]

Give syntax help on the specified SQL command. If command is not specified, then psql will list all the commands for which syntax help is available. If command is an asterisk (*), then syntax help on all SQL commands is shown.

Note

To simplify typing, commands that consists of several words do not have to be quoted. Thus it is fine to type \help alter table.

\H

Turns on HTML query output format. If the HTML format is already on, it is switched back to the default aligned text format. This command is for compatibility and convenience, but see \pset about setting other output options.

\i filename

Reads input from the file filename and executes it as though it had been typed on the keyboard.

Note

If you want to see the lines on the screen as they are read you must set the variable ECHO to all.

\l (or \list)

List all the databases in the server as well as their owners. Append a "+" to the command name to see any descriptions for the databases as well. If your PostgreSQL installation was compiled with multibyte encoding support, the encoding scheme of each database is shown as well.

\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 function lo_export, which acts with the permissions of the user that the database server runs as and on the server's file system.

Tip

Use \lo_list to find out the large object's OID.

Note

See the description of the LO_TRANSACTION variable for important information concerning all large object operations.

\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 one ought to remember if one wants to access the object ever again. For that reason it is recommended to always associate a human-readable comment with every object. Those can then be seen 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.

Note

See the description of the LO_TRANSACTION variable for important information concerning all large object operations.

\lo_list

Shows a list of all PostgreSQL "large objects" currently stored in the database, along with any comments provided for them.

\lo_unlink loid

Deletes the large object with OID loid from the database.

Tip

Use \lo_list to find out the large object's OID.

Note

See the description of the LO_TRANSACTION variable for important information concerning all large object operations.

\o [ {filename | |command} ]

Saves future query results to the file filename or pipes future results into a separate Linux shell to execute command. If no arguments are specified, the query output will be reset to stdout.

"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 does not include error messages.

Tip

To intersperse text output in between query results, use \qecho.

\p

Print the current query buffer to the standard output.

\pset parameter [ value ]

This command sets options affecting the output of query result tables. parameter describes which option is to be set. The semantics of value depend on the option. The adjustable printing options are:

format

Sets the output format to one of unaligned, aligned, html, or latex. Unique abbreviations are allowed. (That would mean one letter is enough.)

"Unaligned" writes all fields of a tuple on a line, separated by the currently active field separator. This is intended to create output that might be intended to be read in by other programs (tab-separated, comma-separated). "Aligned" mode is the standard, human-readable, nicely formatted text output that is default. The "HTML" and "LaTeX" modes put out tables that are intended to be included in documents using the respective mark-up language. Note that these tables are not complete documents. This might not be so dramatic in HTML, but in LaTeX you must have a complete document wrapper.

border

The second argument must be a number. In general, the higher the number the more borders and lines the tables will have, but this depends on the particular format. In HTML mode, this will translate directly into the border=... attribute, in the others only values 0 (no border), 1 (internal dividing lines), and 2 (table frame) make sense.

expanded (or x)

Toggles between regular and expanded format. When expanded format is enabled, all output consists of two columns with the field name on the left and the data on the right. This mode is useful if the data is too wide to fit on the screen in the normal "horizontal" mode.

Expanded mode is supported by all four output modes.

null

The null parameter accepts a second argument, a string that should be printed whenever a field is null. The default is not to print anything, which can easily be mistaken for, say, an empty string. Thus, you might choose to write \pset null '(null)'.

fieldsep

Specifies the field separator to be used in unaligned output mode. That way one can create, for example, tab- or comma-separated output, which other programs might prefer. To set a tab as field separator, type \pset fieldsep '\t'. The default field separator is '|' (a "pipe" symbol).

footer

Toggles the display of the default footer (x rows).

recordsep

Specifies the record (line) separator to use in unaligned output mode. The default is a newline character.

tuples_only (or t)

Toggles between tuples only and full display. Full display may show extra information such as column headers, titles, and various footers. In tuples only mode, only actual table data is shown.

title [ text ]

Sets the table title for any subsequently printed tables. This can be used to give your output descriptive tags. If no argument is given, the title is unset.

tableattr (or T) [ text ]

Allows you to specify any attributes to be placed inside the HTML table tag. This could for example be cellpadding or bgcolor. Note that you probably do not want to specify border here, as that is already taken care of by \pset border.

pager

Toggles the list of a pager to do table output. If the environment variable PAGER is set, the output is piped to the specified program. Otherwise more is used.

In any case, psql only uses the pager if it seems appropriate. That means among other things that the output is to a terminal and that the table would normally not fit on the screen. Because of the modular nature of the printing routines it is not always possible to predict the number of lines that will actually be printed. For that reason psql might not appear very discriminating about when to use the pager and when not to.

\q

Quit the psql program.

\qecho text [ ... ]

This command is identical to \echo except that all output will be written to the query output channel, as set by \o.

\r

Resets (clears) the query buffer.

\s [ filename ]

Print or save the command line history to filename. If filename is omitted, the history is written to the standard output.

Note

The history is loaded automatically every time psql starts up.

\set [ name [ value [ ... ]]]

Sets the internal variable name to value or, if more than one value is given, to the concatenation of all of them. If no second argument is given, the variable is just set with no value. To unset a variable, use the \unset command.

Valid variable names can contain characters, digits, and underscores. See the section about psql variables for details.

Although you are welcome to set any variable to anything you want, psql treats several variables as special. They are documented in the Section called Variables.

Note

This command is totally separate from the SQL command SET.

\t

Toggles the display of output column name headings and row count footer. This command is equivalent to \pset tuples_only and is provided for convenience.

\T table_options

Allows you to specify options to be placed within the table tag in HTML tabular output mode. This command is equivalent to \pset tableattr table_options.

\w {filename | |command}

Outputs the current query buffer to the file filename or pipes it to the Linux command command.

\x

Toggles extended row format mode. It is equivalent to \pset expanded.

\z [ pattern ]

Produces a list of all tables in the database with their appropriate access permissions listed. If an argument is given it is taken as a regular expression which limits the listing to those tables which match it.

test=> \z
Access permissions for database "test"
 Relation |   Access permissions
----------+-------------------------------------
 my_table | {"=r","joe=arwR", "group staff=ar"}
(1 row )
Read this as follows:

  • "=r": PUBLIC has read (SELECT) permission on the table.

  • "joe=arwR": User joe has read, write (UPDATE, DELETE), "append" (INSERT) permissions, and permission to create rules on the table.

  • "group staff=ar": Group staff has SELECT and INSERT permission.

The commands GRANT and REVOKE are used to set access permissions.

\! [ command ]

Escapes to a separate Linux shell or executes the Linux command command. The arguments are not further interpreted, the shell will see them as is.

\?

Get help information about the backslash ("\") commands.