.\\" auto-generated by docbook2man-spec $Revision: 1.25 $ .TH "PSQL" "1" "2002-11-22" "Application" "PostgreSQL Client Applications" .SH NAME psql \- PostgreSQL interactive terminal .SH SYNOPSIS .sp \fBpsql\fR\fR [ \fR\fB\fIoptions\fB \fR\fR]\fR\fR [ \fR\fB\fIdbname\fB\fR [ \fB\fIuser\fB \fR]\fB \fR\fR]\fR .SH "DESCRIPTION" .PP \fBpsql\fR 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. In addition, it provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks. .SH "OPTIONS" .TP \fB-a\fR .TP \fB--echo-all\fR Print all the lines to the screen as they are read. This is more useful for script processing rather than interactive mode. This is equivalent to setting the variable ECHO to all. .TP \fB-A\fR .TP \fB--no-align\fR Switches to unaligned output mode. (The default output mode is otherwise aligned.) .TP \fB-c \fIquery\fB\fR .TP \fB--command \fIquery\fB\fR Specifies that \fBpsql\fR is to execute one query string, \fIquery\fR, and then exit. This is useful in shell scripts. \fIquery\fR must be either a query string that is completely parsable by the backend (i.e., it contains no \fBpsql\fR specific features), or it is a single backslash command. Thus you cannot mix SQL and \fBpsql\fR meta-commands. To achieve that, you could pipe the string into \fBpsql\fR, like this: echo "\\x \\\\ select * from foo;" | psql. .TP \fB-d \fIdbname\fB\fR .TP \fB--dbname \fIdbname\fB\fR Specifies the name of the database to connect to. This is equivalent to specifying \fIdbname\fR as the first non-option argument on the command line. .TP \fB-e\fR .TP \fB--echo-queries\fR Show all queries that are sent to the backend. This is equivalent to setting the variable ECHO to queries. .TP \fB-E\fR .TP \fB--echo-hidden\fR Echoes the actual queries generated by \\d and other backslash commands. You can use this if you wish to include similar functionality into your own programs. This is equivalent to setting the variable ECHO_HIDDEN from within \fBpsql\fR. .TP \fB-f \fIfilename\fB\fR .TP \fB--file \fIfilename\fB\fR Use the file \fIfilename\fR as the source of queries instead of reading queries interactively. After the file is processed, \fBpsql\fR terminates. This is in many ways equivalent to the internal command \fB\\i\fR. If \fIfilename\fR is - (hyphen), then standard input is read. Using this option is subtly different from writing psql < \fIfilename\fR. 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 that you would have gotten had you entered everything by hand. .TP \fB-F \fIseparator\fB\fR .TP \fB--field-separator \fIseparator\fB\fR Use \fIseparator\fR as the field separator. This is equivalent to \fB\\pset fieldsep\fR or \fB\\f\fR. .TP \fB-h \fIhostname\fB\fR .TP \fB--host \fIhostname\fB\fR Specifies the host name of the machine on which the \fBpostmaster\fR is running. If host begins with a slash, it is used as the directory for the Unix-domain socket. .TP \fB-H\fR .TP \fB--html\fR Turns on HTML tabular output. This is equivalent to \\pset format html or the \fB\\H\fR command. .TP \fB-l\fR .TP \fB--list\fR Lists all available databases, then exits. Other non-connection options are ignored. This is similar to the internal command \fB\\list\fR. .TP \fB-o \fIfilename\fB\fR .TP \fB--output \fIfilename\fB\fR Put all query output into file \fIfilename\fR. This is equivalent to the command \fB\\o\fR. .TP \fB-p \fIport\fB\fR .TP \fB--port \fIport\fB\fR Specifies the TCP/IP port or, by omission, the local Unix domain socket file extension on which the \fBpostmaster\fR is listening for connections. Defaults to the value of the \fBPGPORT\fR environment variable or, if not set, to the port specified at compile time, usually 5432. .TP \fB-P \fIassignment\fB\fR .TP \fB--pset \fIassignment\fB\fR Allows you to specify printing options in the style of \fB\\pset\fR on the command line. Note that here you have to separate name and value with an equal sign instead of a space. Thus to set the output format to LaTeX, you could write -P format=latex. .TP \fB-q\fR .TP \fB--quiet\fR Specifies that \fBpsql\fR should 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 \fB-c\fR option. Within \fBpsql\fR you can also set the QUIET variable to achieve the same effect. .TP \fB-R \fIseparator\fB\fR .TP \fB--record-separator \fIseparator\fB\fR Use \fIseparator\fR as the record separator. This is equivalent to the \fB\\pset recordsep\fR command. .TP \fB-s\fR .TP \fB--single-step\fR Run in single-step mode. That means the user is prompted before each query is sent to the backend, with the option to cancel execution as well. Use this to debug scripts. .TP \fB-S\fR .TP \fB--single-line\fR Runs in single-line mode where a newline terminates a query, as a semicolon does. .sp .RS .B "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. .RE .sp .TP \fB-t\fR .TP \fB--tuples-only\fR Turn off printing of column names and result row count footers, etc. It is completely equivalent to the \fB\\t\fR meta-command. .TP \fB-T \fItable_options\fB\fR .TP \fB--table-attr \fItable_options\fB\fR Allows you to specify options to be placed within the HTML table tag. See \fB\\pset\fR for details. .TP \fB-u\fR Makes \fBpsql\fR prompt for the user name and password before connecting to the database. This option is deprecated, as it is conceptually flawed. (Prompting for a non-default user name and prompting for a password because the backend requires it are really two different things.) You are encouraged to look at the \fB-U\fR and \fB-W\fR options instead. .TP \fB-U \fIusername\fB\fR .TP \fB--username \fIusername\fB\fR Connects to the database as the user \fIusername\fR instead of the default. (You must have permission to do so, of course.) .TP \fB-v \fIassignment\fB\fR .TP \fB--set \fIassignment\fB\fR .TP \fB--variable \fIassignment\fB\fR Performs a variable assignment, like the \fB\\set\fR internal 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 just set a variable without a value, use the equal sign but leave off the value. These assignments are done during a very early stage of start-up, so variables reserved for internal purposes might get overwritten later. .TP \fB-V\fR .TP \fB--version\fR Shows the \fBpsql\fR version. .TP \fB-W\fR .TP \fB--password\fR Requests that \fBpsql\fR should prompt for a password before connecting to a database. This will remain set for the entire session, even if you change the database connection with the meta-command \fB\\connect\fR. In the current version, \fBpsql\fR automatically issues a password prompt whenever the backend requests password authentication. Because this is currently based on a hack, the automatic recognition might mysteriously fail, hence this option to force a prompt. If no password prompt is issued and the backend requires password authentication the connection attempt will fail. .TP \fB-x\fR .TP \fB--expanded\fR Turns on extended row format mode. This is equivalent to the command \fB\\x\fR. .TP \fB-X,\fR .TP \fB--no-psqlrc\fR Do not read the start-up file \fI~/.psqlrc\fR. .TP \fB-?\fR .TP \fB--help\fR Shows help about \fBpsql\fR command line arguments. .PP Long options are not available on all platforms. .PP .SH "EXIT STATUS" .PP \fBpsql\fR returns 0 to the shell if it finished normally, 1 if a fatal error of its own (out of memory, file not found) occurs, 2 if the connection to the backend went bad and the session is not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set. .SH "USAGE" .SS "CONNECTING TO A DATABASE" .PP \fBpsql\fR is a regular PostgreSQL client application. 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. \fBpsql\fR can be told about those parameters via command line options, namely \fB-d\fR, \fB-h\fR, \fB-p\fR, and \fB-U\fR 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 also given). Not all these options are required, defaults do apply. If you omit the host name, \fBpsql\fR will connect via a Unix domain socket to a server on the local host. The default port number is compile-time determined. 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 Unix user name, as is the default database name. Note that you can't just connect to any database under any user name. Your database administrator should have informed you about your access rights. To save you some typing you can also set the environment variables \fBPGDATABASE\fR, \fBPGHOST\fR, \fBPGPORT\fR and \fBPGUSER\fR to appropriate values. .PP If the connection could not be made for any reason (e.g., insufficient privileges, postmaster is not running on the server, etc.), \fBpsql\fR will return an error and terminate. .SS "ENTERING QUERIES" .PP In normal operation, \fBpsql\fR provides a prompt with the name of the database to which \fBpsql\fR is currently connected, followed by the string =>. For example, .sp .nf $ \fBpsql testdb\fR Welcome to psql 7.3rc2, the PostgreSQL interactive terminal. Type: \\copyright for distribution terms \\h for help with SQL commands \\? for help on internal slash commands \\g or terminate with semicolon to execute query \\q to quit testdb=> .sp .fi .PP At the prompt, the user may type in SQL queries. Ordinarily, input lines are sent to the backend when a query-terminating semicolon is reached. An end of line does not terminate a query! Thus queries can be spread over several lines for clarity. If the query was sent and without error, the query results are displayed on the screen. .PP Whenever a query is executed, \fBpsql\fR also polls for asynchronous notification events generated by LISTEN [\fBlisten\fR(7)] and NOTIFY [\fBnotify\fR(7)]. .SS "META-COMMANDS" .PP Anything you enter in \fBpsql\fR that begins with an unquoted backslash is a \fBpsql\fR meta-command that is processed by \fBpsql\fR itself. These commands are what makes \fBpsql\fR interesting for administration or scripting. Meta-commands are more commonly called slash or backslash commands. .PP The format of a \fBpsql\fR 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. .PP To include whitespace into an argument you may 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), \\\fIdigits\fR, \\0\fIdigits\fR, and \\0x\fIdigits\fR (the character with the given decimal, octal, or hexadecimal code). .PP If an unquoted argument begins with a colon (:), it is taken as a \fBpsql\fR variable and the value of the variable is used as the argument instead. .PP Arguments that are enclosed in backquotes (`) are taken as a command line that is passed to the shell. The output of the command (with any trailing newline removed) is taken as the argument value. The above escape sequences also apply in backquotes. .PP Some commands take an SQL identifier (such as a table name) as argument. These arguments follow the syntax rules of SQL regarding double quotes: an identifier without double quotes is coerced to lower-case, while whitespace within double quotes is included in the argument. .PP 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 \fBpsql\fR 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. .PP The following meta-commands are defined: .TP \fB\\a\fR 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 \fB\\pset\fR for a general solution. .TP \fB\\cd [\fIdirectory\fB]\fR Change the current working directory to \fIdirectory\fR. Without argument, change to the current user's home directory. .sp .RS .B "Tip:" To print your current working directory, use \\!pwd. .RE .sp .TP \fB\\C [ \fItitle\fB ]\fR 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 \fItitle\fR. (The name of this command derives from ``caption'', as it was previously only used to set the caption in an HTML table.) .TP \fB\\connect (or \\c) [ \fIdbname\fB [ \fIusername\fB ] ]\fR Establishes a connection to a new database and/or under a user name. The previous connection is closed. If \fIdbname\fR is - the current database name is assumed. If \fIusername\fR is omitted the current user name is assumed. As a special rule, \fB\\connect\fR without any arguments will connect to the default database as the default user (as you would have gotten by starting \fBpsql\fR without any arguments). If the connection attempt failed (wrong user name, access denied, etc.), the previous connection will be kept if and only if \fBpsql\fR is in interactive mode. When executing a non-interactive script, processing will immediately stop with an 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. .TP \fB\\copy \fItable\fB\fR Performs a frontend (client) copy. This is an operation that runs an SQL COPY [\fBcopy\fR(7)] command, but instead of the backend's reading or writing the specified file, \fBpsql\fR reads or writes the file and routes the data between the backend and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required. The syntax of the command is similar to that of the SQL \fBCOPY\fR command (see its description for the details). Note that, because of this, special parsing rules apply to the \fB\\copy\fR command. In particular, the variable substitution rules and backslash escapes do not apply. .sp .RS .B "Tip:" This operation is not as efficient as the SQL \fBCOPY\fR command because all data must pass through the client/server IP or socket connection. For large amounts of data the other technique may be preferable. .RE .sp .sp .RS .B "Note:" Note the difference in interpretation of stdin and stdout between frontend and backend copies: in a frontend copy these always refer to \fBpsql\fR's input and output stream. On a backend copy stdin comes from wherever the \fBCOPY\fR itself came from (for example, a script run with the \fB-f\fR option), and stdout refers to the query output stream (see \fB\\o\fR meta-command below). .RE .sp .TP \fB\\copyright\fR Shows the copyright and distribution terms of \fBPostgreSQL\fR. .TP \fB\\d [ \fIpattern\fB ]\fR For each relation (table, view, index, or sequence) matching the \fIpattern\fR, show all columns, their types, and any special attributes such as NOT NULL or defaults, if any. Associated indexes, constraints, rules, and triggers are also shown, as is the view definition if the relation is a view. (``Matching the pattern'' is defined below.) The command form \\d+ is identical, but any comments associated with the table columns are shown as well. .sp .RS .B "Note:" If \fB\\d\fR is used without a \fIpattern\fR argument, it is equivalent to \fB\\dtvs\fR which will show a list of all tables, views, and sequences. This is purely a convenience measure. .RE .sp .TP \fB\\da [ \fIpattern\fB ]\fR Lists all available aggregate functions, together with the data type they operate on. If \fIpattern\fR (a regular expression) is specified, only matching aggregates are shown. .TP \fB\\dd [ \fIpattern\fB ]\fR Shows the descriptions of objects matching the \fIpattern\fR, or of all visible objects if no argument is given. But in either case, only objects that have a description are listed. (``Object'' covers aggregates, functions, operators, types, relations (tables, views, indexes, sequences, large objects), rules, and triggers.) For example: .sp .nf => \fB\\dd version\fR Object descriptions Schema | Name | Object | Description ------------+---------+----------+--------------------------- pg_catalog | version | function | PostgreSQL version string (1 row) .sp .fi Descriptions for objects can be created with the \fBCOMMENT ON\fR SQL command. .sp .RS .B "Note:" PostgreSQL stores the object descriptions in the \fBpg_description\fR system table. .RE .sp .TP \fB\\dD [ \fIpattern\fB ]\fR Lists all available domains (derived types). If \fIpattern\fR is specified, only matching domains are shown. .TP \fB\\df [ \fIpattern\fB ]\fR Lists available functions, together with their argument and return types. If \fIpattern\fR is specified, only matching functions are shown. If the form \\df+ is used, additional information about each function, including language and description, is shown. .sp .RS .B "Note:" To reduce clutter, \\df does not show data type I/O functions. This is implemented by ignoring functions that accept or return type \fBcstring\fR. .RE .sp .TP \fB\\distvS [ \fIpattern\fB ]\fR 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 these letters, in any order, to obtain a listing of all the matching objects. The letter S restricts the listing to system objects; without S, only non-system objects are shown. If ``+'' is appended to the command name, each object is listed with its associated description, if any. If a \fIpattern\fR is specified, only objects whose name matches the pattern are listed. .TP \fB\\dl\fR This is an alias for \fB\\lo_list\fR, which shows a list of large objects. .TP \fB\\do [ \fIpattern\fB ]\fR Lists available operators with their operand and return types. If a \fIpattern\fR is specified, only operators whose name matches the pattern are listed. .TP \fB\\dp [ \fIpattern\fB ]\fR Produces a list of all available tables with their associated access permissions. If a \fIpattern\fR is specified, only tables whose name matches the pattern are listed. The commands \fBgrant\fR(7) and \fBrevoke\fR(7) are used to set access permissions. See \fBgrant\fR(7) for more information. .TP \fB\\dT [ \fIpattern\fB ]\fR Lists all data types or only those that match \fIpattern\fR. The command form \\dT+ shows extra information. .TP \fB\\du [ \fIpattern\fB ]\fR Lists all database users, or only those that match \fIpattern\fR. .TP \fB\\edit (or \\e) [ \fIfilename\fB ]\fR If \fIfilename\fR 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 \fBpsql\fR, where the whole buffer is treated as a single line. (Thus you cannot make scripts this way. Use \fB\\i\fR for that.) This means also that if the query ends with (or rather contains) a semicolon, it is immediately executed. In other cases it will merely wait in the query buffer. .sp .RS .B "Tip:" \fBpsql\fR searches the environment variables \fBPSQL_EDITOR\fR, \fBEDITOR\fR, and \fBVISUAL\fR (in that order) for an editor to use. If all of them are unset, \fI/bin/vi\fR is run. .RE .sp .TP \fB\\echo \fItext\fB [ ... ]\fR 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: .sp .nf => \fB\\echo `date`\fR Tue Oct 26 21:40:57 CEST 1999 .sp .fi If the first argument is an unquoted -n the the trailing newline is not written. .sp .RS .B "Tip:" If you use the \fB\\o\fR command to redirect your query output you may wish to use \fB\\qecho\fR instead of this command. .RE .sp .TP \fB\\encoding [ \fIencoding\fB ]\fR Sets the client encoding, if you are using multibyte encodings. Without an argument, this command shows the current encoding. .TP \fB\\f [ \fIstring\fB ]\fR Sets the field separator for unaligned query output. The default is pipe (|). See also \fB\\pset\fR for a generic way of setting output options. .TP \fB\\g [ { \fIfilename\fB | |\fIcommand\fB } ]\fR Sends the current query input buffer to the backend and optionally saves the output in \fIfilename\fR or pipes the output into a separate Unix shell to execute \fIcommand\fR. A bare \\g is virtually equivalent to a semicolon. A \\g with argument is a ``one-shot'' alternative to the \fB\\o\fR command. .TP \fB\\help (or \\h) [ \fIcommand\fB ]\fR Give syntax help on the specified SQL command. If \fIcommand\fR is not specified, then \fBpsql\fR will list all the commands for which syntax help is available. If \fIcommand\fR is an asterisk (``*''), then syntax help on all SQL commands is shown. .sp .RS .B "Note:" To simplify typing, commands that consists of several words do not have to be quoted. Thus it is fine to type \fB\\help alter table\fR. .RE .sp .TP \fB\\H\fR 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 \fB\\pset\fR about setting other output options. .TP \fB\\i \fIfilename\fB\fR Reads input from the file \fIfilename\fR and executes it as though it had been typed on the keyboard. .sp .RS .B "Note:" If you want to see the lines on the screen as they are read you must set the variable ECHO to all. .RE .sp .TP \fB\\l (or \\list)\fR 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. .TP \fB\\lo_export \fIloid\fB \fIfilename\fB\fR Reads the large object with OID \fIloid\fR from the database and writes it to \fIfilename\fR. Note that this is subtly different from the server function \fBlo_export\fR, which acts with the permissions of the user that the database server runs as and on the server's file system. .sp .RS .B "Tip:" Use \fB\\lo_list\fR to find out the large object's OID. .RE .sp .sp .RS .B "Note:" See the description of the LO_TRANSACTION variable for important information concerning all large object operations. .RE .sp .TP \fB\\lo_import \fIfilename\fB [ \fIcomment\fB ]\fR Stores the file into a PostgreSQL ``large object''. Optionally, it associates the given comment with the object. Example: .sp .nf foo=> \fB\\lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'\fR lo_import 152801 .sp .fi 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 \fB\\lo_list\fR command. Note that this command is subtly different from the server-side \fBlo_import\fR because it acts as the local user on the local file system, rather than the server's user and file system. .sp .RS .B "Note:" See the description of the LO_TRANSACTION variable for important information concerning all large object operations. .RE .sp .TP \fB\\lo_list\fR Shows a list of all PostgreSQL ``large objects'' currently stored in the database, along with any comments provided for them. .TP \fB\\lo_unlink \fIloid\fB\fR Deletes the large object with OID \fIloid\fR from the database. .sp .RS .B "Tip:" Use \fB\\lo_list\fR to find out the large object's OID. .RE .sp .sp .RS .B "Note:" See the description of the LO_TRANSACTION variable for important information concerning all large object operations. .RE .sp .TP \fB\\o [ {\fIfilename\fB | |\fIcommand\fB} ]\fR Saves future query results to the file \fIfilename\fR or pipes future results into a separate Unix shell to execute \fIcommand\fR. If no arguments are specified, the query output will be reset to \fIstdout\fR. ``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 \fB\\d\fR), but not error messages. .sp .RS .B "Tip:" To intersperse text output in between query results, use \fB\\qecho\fR. .RE .sp .TP \fB\\p\fR Print the current query buffer to the standard output. .TP \fB\\pset \fIparameter\fB [ \fIvalue\fB ]\fR This command sets options affecting the output of query result tables. \fIparameter\fR describes which option is to be set. The semantics of \fIvalue\fR depend thereon. Adjustable printing options are: .RS .TP \fBformat\fR 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. They are not complete documents! (This might not be so dramatic in HTML, but in LaTeX you must have a complete document wrapper.) .TP \fBborder\fR 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. .TP \fBexpanded (or x)\fR Toggles between regular and expanded format. When expanded format is enabled, all output has two columns with the field name on the left and the data on the right. This mode is useful if the data wouldn't fit on the screen in the normal ``horizontal'' mode. Expanded mode is supported by all four output modes. .TP \fBnull\fR The second argument is 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, one might choose to write \\pset null \&'(null)'. .TP \fBfieldsep\fR 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). .TP \fBfooter\fR Toggles the display of the default footer (x rows). .TP \fBrecordsep\fR Specifies the record (line) separator to use in unaligned output mode. The default is a newline character. .TP \fBtuples_only (or t)\fR 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. .TP \fBtitle [ \fItext\fB ]\fR 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. .sp .RS .B "Note:" This formerly only affected HTML mode. You can now set titles in any output format. .RE .sp .TP \fBtableattr (or T) [ \fItext\fB ]\fR 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 don't want to specify border here, as that is already taken care of by \\pset border. .TP \fBpager\fR Toggles the use of a pager for query and \fBpsql\fR help output. If the environment variable \fBPAGER\fR is set, the output is piped to the specified program. Otherwise a platform-dependent default (such as \fImore\fR) is used. In any case, \fBpsql\fR 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 \fBpsql\fR might not appear very discriminating about when to use the pager. .RE .PP Illustrations on how these different formats look can be seen in the Examples [\fBpsql\fR(1)] section. .sp .RS .B "Tip:" There are various shortcut commands for \fB\\pset\fR. See \fB\\a\fR, \fB\\C\fR, \fB\\H\fR, \fB\\t\fR, \fB\\T\fR, and \fB\\x\fR. .RE .sp .sp .RS .B "Note:" It is an error to call \fB\\pset\fR without arguments. In the future this call might show the current status of all printing options. .RE .sp .TP \fB\\q\fR Quit the \fBpsql\fR program. .TP \fB\\qecho \fItext\fB [ ... ]\fR This command is identical to \fB\\echo\fR except that all output will be written to the query output channel, as set by \fB\\o\fR. .TP \fB\\r\fR Resets (clears) the query buffer. .TP \fB\\s [ \fIfilename\fB ]\fR Print or save the command line history to \fIfilename\fR. If \fIfilename\fR is omitted, the history is written to the standard output. This option is only available if \fBpsql\fR is configured to use the GNU history library. .sp .RS .B "Note:" In the current version, it is no longer necessary to save the command history, since that will be done automatically on program termination. The history is also loaded automatically every time \fBpsql\fR starts up. .RE .sp .TP \fB\\set [ \fIname\fB [ \fIvalue\fB [ ... ]]]\fR Sets the internal variable \fIname\fR to \fIvalue\fR 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 \fB\\unset\fR command. Valid variable names can contain characters, digits, and underscores. See the section about \fBpsql\fR variables for details. Although you are welcome to set any variable to anything you want, \fBpsql\fR treats several variables as special. They are documented in the section about variables. .sp .RS .B "Note:" This command is totally separate from the SQL command SET [\fBset\fR(7)]. .RE .sp .TP \fB\\t\fR 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. .TP \fB\\T \fItable_options\fB\fR Allows you to specify options to be placed within the table tag in HTML tabular output mode. This command is equivalent to \\pset tableattr \fItable_options\fR. .TP \fB\\timing\fR Toggles a display of how long each SQL statement takes, in milliseconds. .TP \fB\\w {\fIfilename\fB | \fI|command\fB}\fR Outputs the current query buffer to the file \fIfilename\fR or pipes it to the Unix command \fIcommand\fR. .TP \fB\\x\fR Toggles extended row format mode. As such it is equivalent to \\pset expanded. .TP \fB\\z [ \fIpattern\fB ]\fR Produces a list of all available tables with their associated access permissions. If a \fIpattern\fR is specified, only tables whose name matches the pattern are listed. The commands \fBgrant\fR(7) and \fBrevoke\fR(7) are used to set access permissions. See \fBgrant\fR(7) for more information. This is an alias for \fB\\dp\fR (``display permissions''). .TP \fB\\! [ \fIcommand\fB ]\fR Escapes to a separate Unix shell or executes the Unix command \fIcommand\fR. The arguments are not further interpreted, the shell will see them as is. .TP \fB\\?\fR Get help information about the backslash (``\\'') commands. .PP .PP The various \\d commands accept a \fIpattern\fR parameter to specify the object name(s) to be displayed. Patterns are interpreted similarly to SQL identifiers, in that 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. .PP More interestingly, \\d patterns allow the use of * to mean ``any sequence of characters'', and ? to mean ``any single character''. (This notation is comparable to Unix shell filename patterns.) Advanced users can also use regular-expression notations such as character classes, for example [0-9] to match ``any digit''. To make any of these pattern-matching characters be interpreted literally, surround it with double quotes. .PP A pattern that contains an (unquoted) dot is interpreted as a schema name pattern followed by an object name pattern. For example, \\dt foo*.bar* displays all tables in schemas whose name starts with foo and whose table name starts with bar. If no dot appears, then the pattern matches only objects that are visible in the current schema search path. .PP Whenever the \fIpattern\fR parameter is omitted completely, the \\d commands display all objects that are visible in the current schema search path. To see all objects in the database, use the pattern *.*. .SS "ADVANCED FEATURES" .SS "VARIABLES" .PP \fBpsql\fR provides variable substitution features similar to common Unix command shells. This feature is new and not very sophisticated, yet, but there are plans to expand it in the future. Variables are simply name/value pairs, where the value can be any string of any length. To set variables, use the \fBpsql\fR meta-command \fB\\set\fR: .sp .nf testdb=> \fB\\set foo bar\fR .sp .fi sets the variable ``foo'' to the value ``bar''. To retrieve the content of the variable, precede the name with a colon and use it as the argument of any slash command: .sp .nf testdb=> \fB\\echo :foo\fR bar .sp .fi .sp .RS .B "Note:" The arguments of \fB\\set\fR are subject to the same substitution rules as with other commands. Thus 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 is no way to do anything useful with these constructs. On the other hand, \\set bar :foo is a perfectly valid way to copy a variable. .RE .sp .PP If you call \fB\\set\fR without a second argument, the variable is simply set, but has no value. To unset (or delete) a variable, use the command \fB\\unset\fR. .PP \fBpsql\fR's internal variable names can consist of letters, numbers, and underscores in any order and any number of them. A number of regular variables are treated specially by \fBpsql\fR. They indicate certain option settings that can be changed at run time by altering the value of the variable or represent some state of the application. Although you can use these variables for any other purpose, this is not recommended, as the program behavior might grow really strange really quickly. By convention, all specially treated variables consist of all upper-case letters (and possibly numbers and underscores). To ensure maximum compatibility in the future, avoid such variables. A list of all specially treated variables follows. .TP \fBDBNAME\fR 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 unset. .TP \fBECHO\fR If set to ``all'', all lines entered or from a script are written to the standard output before they are parsed or executed. To specify this on program start-up, use the switch \fB-a\fR. If set to ``queries'', \fBpsql\fR merely prints all queries as they are sent to the backend. The option for this is \fB-e\fR. .TP \fBECHO_HIDDEN\fR When this variable is set and a backslash command queries the database, the query is first shown. This way you can study the PostgreSQL internals and provide similar functionality in your own programs. If you set the variable to the value noexec, the queries are just shown but are not actually sent to the backend and executed. .TP \fBENCODING\fR The current client multibyte encoding. If you are not set up to use multibyte characters, this variable will always contain ``SQL_ASCII''. .TP \fBHISTCONTROL\fR If this variable is set to ignorespace, lines which begin with a space are not entered into the history list. If set to a value of ignoredups, lines matching the previous history line are not entered. A value of ignoreboth combines the two options. If unset, or if set to any other value than those above, all lines read in interactive mode are saved on the history list. .sp .RS .B "Note:" This feature was shamelessly plagiarized from \fBbash\fR. .RE .sp .TP \fBHISTSIZE\fR The number of commands to store in the command history. The default value is 500. .sp .RS .B "Note:" This feature was shamelessly plagiarized from \fBbash\fR. .RE .sp .TP \fBHOST\fR The database server host you are currently connected to. This is set every time you connect to a database (including program start-up), but can be unset. .TP \fBIGNOREEOF\fR If unset, sending an EOF character (usually \fBControl\fR+\fBD\fR) to an interactive session of \fBpsql\fR will terminate the application. If set to a numeric value, that many EOF characters are ignored before the application terminates. If the variable is set but has no numeric value, the default is 10. .sp .RS .B "Note:" This feature was shamelessly plagiarized from \fBbash\fR. .RE .sp .TP \fBLASTOID\fR The value of the last affected OID, as returned from an \fBINSERT\fR or \fBlo_insert\fR command. This variable is only guaranteed to be valid until after the result of the next SQL command has been displayed. .TP \fBLO_TRANSACTION\fR If you use the PostgreSQL large object interface to specially store data that does not fit into one tuple, all the operations must be contained in a transaction block. (See the documentation of the large object interface for more information.) Since \fBpsql\fR has no way to tell if you already have a transaction in progress when you call one of its internal commands (\fB\\lo_export\fR, \fB\\lo_import\fR, \fB\\lo_unlink\fR) it must take some arbitrary action. This action could either be to roll back any transaction that might already be in progress, or to commit any such transaction, or to do nothing at all. In the last case you must provide your own \fBBEGIN TRANSACTION\fR/\fBCOMMIT\fR block or the results will be unpredictable (usually resulting in the desired action's not being performed in any case). To choose what you want to do you set this variable to one of ``rollback'', ``commit'', or ``nothing''. The default is to roll back the transaction. If you just want to load one or a few objects this is fine. However, if you intend to transfer many large objects, it might be advisable to provide one explicit transaction block around all commands. .TP \fBON_ERROR_STOP\fR By default, if non-interactive scripts encounter an error, such as a malformed SQL query or internal meta-command, processing continues. This has been the traditional behavior of \fBpsql\fR but it is sometimes not desirable. If this variable is set, script processing will immediately terminate. If the script was called from another script it will terminate in the same fashion. If the outermost script was not called from an interactive \fBpsql\fR session but rather using the \fB-f\fR option, \fBpsql\fR will return error code 3, to distinguish this case from fatal error conditions (error code 1). .TP \fBPORT\fR The database server port to which you are currently connected. This is set every time you connect to a database (including program start-up), but can be unset. .TP \fBPROMPT1\fR .TP \fBPROMPT2\fR .TP \fBPROMPT3\fR These specify what the prompt \fBpsql\fR issues is supposed to look like. See ``Prompting [\fBpsql\fR(1)]'' below. .TP \fBQUIET\fR This variable is equivalent to the command line option \fB-q\fR. It is probably not too useful in interactive mode. .TP \fBSINGLELINE\fR This variable is set by the command line option \fB-S\fR. You can unset or reset it at run time. .TP \fBSINGLESTEP\fR This variable is equivalent to the command line option \fB-s\fR. .TP \fBUSER\fR The database user you are currently connected as. This is set every time you connect to a database (including program start-up), but can be unset. .PP .SS "SQL INTERPOLATION" .PP An additional useful feature of \fBpsql\fR variables is that you can substitute (``interpolate'') them into regular SQL statements. The syntax for this is again to prepend the variable name with a colon (:). .sp .nf testdb=> \fB\\set foo 'my_table'\fR testdb=> \fBSELECT * FROM :foo;\fR .sp .fi would then query the table my_table. The value of the variable is copied literally, so it can even contain unbalanced quotes or backslash commands. You must make sure that it makes sense where you put it. Variable interpolation will not be performed into quoted SQL entities. .PP A popular application of this facility is to refer to the last inserted OID in subsequent statements to build a foreign key scenario. Another possible use of this mechanism is to copy the contents of a file into a field. First load the file into a variable and then proceed as above. .sp .nf testdb=> \fB\\set content '\\'' `cat my_file.txt` '\\''\fR testdb=> \fBINSERT INTO my_table VALUES (:content);\fR .sp .fi One possible problem with this approach is that \fImy_file.txt\fR might contain single quotes. These need to be escaped so that they don't cause a syntax error when the third line is processed. This could be done with the program \fBsed\fR: .sp .nf testdb=> \fB\\set content '\\'' `sed -e "s/'/\\\\\\\\\\\\'/g" < my_file.txt` '\\''\fR .sp .fi Observe the correct number of backslashes (6)! You can resolve it this way: After \fBpsql\fR has parsed this line, it passes sed -e "s/'/\\\\\\'/g" < my_file.txt to the shell. The shell will do its own thing inside the double quotes and execute \fIsed\fR with the arguments -e and s/'/\\\\'/g. When \fBsed\fR parses this it will replace the two backslashes with a single one and then do the substitution. Perhaps at one point you thought it was great that all Unix commands use the same escape character. And this is ignoring the fact that you might have to escape all backslashes as well because SQL text constants are also subject to certain interpretations. In that case you might be better off preparing the file externally. .PP Since colons may legally appear in queries, the following rule applies: If the variable is not set, the character sequence ``colon+name'' is not changed. In any case you can escape a colon with a backslash to protect it from interpretation. (The colon syntax for variables is standard SQL for embedded query languages, such as \fBecpg\fR. The colon syntax for array slices and type casts are PostgreSQL extensions, hence the conflict.) .SS "PROMPTING" .PP The prompts \fBpsql\fR issues can be customized to your preference. The three variables PROMPT1, PROMPT2, and PROMPT3 contain strings and special escape sequences that describe the appearance of the prompt. Prompt 1 is the normal prompt that is issued when \fBpsql\fR requests a new query. Prompt 2 is issued when more input is expected during query input because the query was not terminated with a semicolon or a quote was not closed. Prompt 3 is issued when you run an SQL \fBCOPY\fR command and you are expected to type in the tuples on the terminal. .PP The value of the respective prompt variable is printed literally, except where a percent sign (``%'') is encountered. Depending on the next character, certain other text is substituted instead. Defined substitutions are: .TP \fB%M\fR The full host name (with domain name) of the database server, or [local] if the connection is over a Unix domain socket, or [local:\fI/dir/name\fR], if the Unix domain socket is not at the compiled in default location. .TP \fB%m\fR The host name of the database server, truncated after the first dot, or [local] if the connection is over a Unix domain socket. .TP \fB%>\fR The port number at which the database server is listening. .TP \fB%n\fR The user name you are connected as (not your local system user name). .TP \fB%/\fR The name of the current database. .TP \fB%~\fR Like %/, but the output is ``~'' (tilde) if the database is your default database. .TP \fB%#\fR If the current user is a database superuser, then a ``#'', otherwise a ``>''. .TP \fB%R\fR In prompt 1 normally ``='', but ``^'' if in single-line mode, and ``!'' if the session is disconnected from the database (which can happen if \fB\\connect\fR fails). In prompt 2 the sequence is replaced by ``-'', ``*'', a single quote, or a double quote, depending on whether \fBpsql\fR expects more input because the query wasn't terminated yet, because you are inside a /* ... */ comment, or because you are inside a quote. In prompt 3 the sequence doesn't resolve to anything. .TP \fB%\fIdigits\fB\fR If \fIdigits\fR starts with 0x the rest of the characters are interpreted as a hexadecimal digit and the character with the corresponding code is substituted. If the first digit is 0 the characters are interpreted as on octal number and the corresponding character is substituted. Otherwise a decimal number is assumed. .TP \fB%:\fIname\fB:\fR The value of the \fBpsql\fR, variable \fIname\fR. See the section ``Variables [\fBpsql\fR(1)]'' for details. .TP \fB%`\fIcommand\fB`\fR The output of \fIcommand\fR, similar to ordinary ``back-tick'' substitution. .PP To insert a percent sign into your prompt, write %%. The default prompts are equivalent to \&'%/%R%# ' for prompts 1 and 2, and \&'>> ' for prompt 3. .sp .RS .B "Note:" This feature was shamelessly plagiarized from \fBtcsh\fR. .RE .sp .SS "COMMAND-LINE EDITING" .PP \fBpsql\fR supports the \fBReadline\fR library for convenient line editing and retrieval. The command history is stored in a file named \fI.psql_history\fR in your home directory and is reloaded when \fBpsql\fR starts up. Tab-completion is also supported, although the completion logic makes no claim to be an SQL parser. When available, \fBpsql\fR is automatically built to use these features. If for some reason you do not like the tab completion, you can turn if off by putting this in a file named \fI\&.inputrc\fR in your home directory: .sp .nf $if psql set disable-completion on $endif .sp .fi (This is not a \fBpsql\fR but a \fBreadline\fR feature. Read its documentation for further details.) .SH "ENVIRONMENT" .TP \fBHOME\fR Directory for initialization file (\fI.psqlrc\fR) and command history file (\fI.psql_history\fR). .TP \fBPAGER\fR If the query results do not fit on the screen, they are piped through this command. Typical values are more or less. The default is platform-dependent. The use of the pager can be disabled by using the \fB\\pset\fR command. .TP \fBPGDATABASE\fR Default database to connect to .TP \fBPGHOST\fR .TP \fBPGPORT\fR .TP \fBPGUSER\fR Default connection parameters .TP \fBPSQL_EDITOR\fR .TP \fBEDITOR\fR .TP \fBVISUAL\fR Editor used by the \fB\\e\fR command. The variables are examined in the order listed; the first that is set is used. .TP \fBSHELL\fR Command executed by the \fB\\!\fR command. .TP \fBTMPDIR\fR Directory for storing temporary files. The default is \fI/tmp\fR. .SH "FILES" .TP 0.2i \(bu Before starting up, \fBpsql\fR attempts to read and execute commands from the file \fI$HOME/.psqlrc\fR. It could be used to set up the client or the server to taste (using the \fB\\set \fRand \fBSET\fR commands). .TP 0.2i \(bu The command-line history is stored in the file \fI$HOME/.psql_history\fR. .SH "NOTES" .TP 0.2i \(bu In an earlier life \fBpsql\fR allowed the first argument of a single-letter backslash command to start directly after the command, without intervening whitespace. For compatibility this is still supported to some extent, but I am not going to explain the details here as this use is discouraged. If you get strange messages, keep this in mind. For example .sp .nf testdb=> \fB\\foo\fR Field separator is "oo", .sp .fi which is perhaps not what one would expect. .TP 0.2i \(bu \fBpsql\fR only works smoothly with servers of the same version. That does not mean other combinations will fail outright, but subtle and not-so-subtle problems might come up. Backslash commands are particularly likely to fail if the server is of a different version. .TP 0.2i \(bu Pressing Control-C during a ``copy in'' (data sent to the server) doesn't show the most ideal of behaviors. If you get a message such as ``COPY state must be terminated first'', simply reset the connection by entering \\c - -. .SH "EXAMPLES" .sp .RS .B "Note:" This section only shows a few examples specific to \fBpsql\fR. If you want to learn SQL or get familiar with PostgreSQL, you might wish to read the Tutorial that is included in the distribution. .RE .sp .PP The first example shows how to spread a query over several lines of input. Notice the changing prompt: .sp .nf testdb=> \fBCREATE TABLE my_table (\fR testdb(> \fB first integer not null default 0,\fR testdb(> \fB second text\fR testdb-> \fB);\fR CREATE .sp .fi Now look at the table definition again: .sp .nf testdb=> \fB\\d my_table\fR Table "my_table" Attribute | Type | Modifier -----------+---------+-------------------- first | integer | not null default 0 second | text | .sp .fi At this point you decide to change the prompt to something more interesting: .sp .nf testdb=> \fB\\set PROMPT1 '%n@%m %~%R%# '\fR peter@localhost testdb=> .sp .fi Let's assume you have filled the table with data and want to take a look at it: .sp .nf peter@localhost testdb=> SELECT * FROM my_table; first | second -------+-------- 1 | one 2 | two 3 | three 4 | four (4 rows) .sp .fi You can make this table look differently by using the \fB\\pset\fR command: .sp .nf peter@localhost testdb=> \fB\\pset border 2\fR Border style is 2. peter@localhost testdb=> \fBSELECT * FROM my_table;\fR +-------+--------+ | first | second | +-------+--------+ | 1 | one | | 2 | two | | 3 | three | | 4 | four | +-------+--------+ (4 rows) peter@localhost testdb=> \fB\\pset border 0\fR Border style is 0. peter@localhost testdb=> \fBSELECT * FROM my_table;\fR first second ----- ------ 1 one 2 two 3 three 4 four (4 rows) peter@localhost testdb=> \fB\\pset border 1\fR Border style is 1. peter@localhost testdb=> \fB\\pset format unaligned\fR Output format is unaligned. peter@localhost testdb=> \fB\\pset fieldsep ","\fR Field separator is ",". peter@localhost testdb=> \fB\\pset tuples_only\fR Showing only tuples. peter@localhost testdb=> \fBSELECT second, first FROM my_table;\fR one,1 two,2 three,3 four,4 .sp .fi Alternatively, use the short commands: .sp .nf peter@localhost testdb=> \fB\\a \\t \\x\fR Output format is aligned. Tuples only is off. Expanded display is on. peter@localhost testdb=> \fBSELECT * FROM my_table;\fR -[ RECORD 1 ]- first | 1 second | one -[ RECORD 2 ]- first | 2 second | two -[ RECORD 3 ]- first | 3 second | three -[ RECORD 4 ]- first | 4 second | four .sp .fi