- Работаем с PostgreSQL через командную строку в Linux
- Установка PostgreSQL на Linux (Mint)
- PostgreSQL Подключение, Пользователи (Роли) и Базы Данных
- PostgreSQL создание новой роли и базы данных
- Включить удаленный PostgreSQL доступ для пользователей
- Полезные команды PostgreSQL
- Выбор shema psql в консоли:
- Sequences
- 17 Practical psql Commands That You Don’t Want To Miss
- 1) Connect to PostgreSQL database
- 2) Switch connection to a new database
- 3) List available databases
- 4) List available tables
- 5) Describe a table
- 6) List available schema
- 7) List available functions
- 8) List available views
- 9) List users and their roles
- 10) Execute the previous command
- 11) Command history
- 12) Execute psql commands from a file
- 13) Get help on psql commands
- 14) Turn on query execution time
- 15) Edit command in your own editor
- 16) Switch output options
- 17) Quit psql
- psql — Unix, Linux Command
- SYNOPSIS
- DESCRIPTION
- OPTIONS
- META-COMMANDS
- ADVANCED FEATURES
- VARIABLES
- SQL INTERPOLATION
- COMMAND-LINE EDITING
- ENVIRONMENT
- FILES
- NOTES
- NOTES FOR WINDOWS USERS
- EXAMPLES
Работаем с PostgreSQL через командную строку в Linux
Установка PostgreSQL на Linux (Mint)
Для подключения к базе данных PostgreSQL понадобится установленный PostgreSQL клиент:
Для установки PostgreSQL сервера:
Проверим, можем ли мы подключиться к базе данных PostgreSQL:
Вывод команды должен быть примерно таким:
PostgreSQL Подключение, Пользователи (Роли) и Базы Данных
Логин в только что установленный postgreSQL сервер нужно производить под именем пользователя postgres:
Для подключения к базе данных PostgreSQL можно использовать команду:
Если такая команда не просит ввести пароль пользователя, то можно еще добавить опцию -W.
После ввода пароля и успешного подключения к базе данных PostgreSQL, можно посылать SQL-запросы и psql-команды.
PostgreSQL создание новой роли и базы данных
Создать новую роль c именем admin (указывайте нужное имя):
Создание новой базы данных:
Дать права роли на базу данных:
Включить удаленный PostgreSQL доступ для пользователей
Нам нужно отредактировать файл /etc/postgresql/ /main/pg_hba.conf, задав опцию md5 вместо peer.
может быть 10, 11, 12 и т.д.
После этого сделать restart PostgreSQL:
Полезные команды PostgreSQL
Выйти из клиента PostgreSQL:
\q
Показать список баз данных PostgreSQL:
\l
Показать список таблиц:
\dt
Показать список пользователей (ролей):
\du
Показать структуру таблицы:
Переименовать базу данных:
Удалить базу данных:
Изменить текущую базу данных в PostgreSQL (вы не сможете переименовать или удалить текущую базу данных):
\connect db_name или более короткий alias: \c db_name
Удалить роль (пользователя):
Роль не будет удалена, если у нее есть привелегии — возникнет ошибка ERROR: role cannot be dropped because some objects depend on it .
Нужно удалить привелегии у роли, например если нужно удалить роль admin2, нужно выполнить последовательность комманд с Drop Owned:
Дать права пользователю/роли на логин ( role is not permitted to log in ):
Выбор shema psql в консоли:
Посмотреть список всех схем:
Подключиться к конкретной схеме:
Sequences
Получить имена всех созданных sequences:
Получить последнее значение sequence, которые будет присвоено новой вставляемой в таблицу записи:
Источник
17 Practical psql Commands That You Don’t Want To Miss
Summary: in this tutorial, we give you a list of common psql commands that help you query data from the PostgreSQL database server faster and more effectively.
1) Connect to PostgreSQL database
The following command connects to a database under a specific user. After pressing Enter PostgreSQL will ask for the password of the user.
For example, to connect to dvdrental database under postgres user, you use the following command:
If you want to connect to a database that resides on another host, you add the -h option as follows:
In case you want to use SSL mode for the connection, just specify it as shown in the following command:
2) Switch connection to a new database
Once you are connected to a database, you can switch the connection to a new database under a user specified by user . The previous connection will be closed. If you omit the user parameter, the current user is assumed.
The following command connects to dvdrental database under postgres user:
3) List available databases
To list all databases in the current PostgreSQL database server, you use \l command:
4) List available tables
To list all tables in the current database, you use \dt command:
Note that this command shows the only table in the currently connected database.
5) Describe a table
To describe a table such as a column, type, modifiers of columns, etc., you use the following command:
6) List available schema
To list all schemas of the currently connected database, you use the \dn command.
7) List available functions
To list available functions in the current database, you use the \df command.
8) List available views
To list available views in the current database, you use the \dv command.
9) List users and their roles
To list all users and their assign roles, you use \du command:
10) Execute the previous command
To retrieve the current version of PostgreSQL server, you use the version() function as follows:
Now, you want to save time typing the previous command again, you can use \g command to execute the previous command:
psql executes the previous command again, which is the SELECT statement,.
11) Command history
To display command history, you use the \s command.
If you want to save the command history to a file, you need to specify the file name followed the \s command as follows:
12) Execute psql commands from a file
In case you want to execute psql commands from a file, you use \i command as follows:
13) Get help on psql commands
To know all available psql commands, you use the \? command.
To get help on specific PostgreSQL statement, you use the \h command.
For example, if you want to know detailed information on ALTER TABLE statement, you use the following command:
14) Turn on query execution time
To turn on query execution time, you use the \timing command.
You use the same command \timing to turn it off.
15) Edit command in your own editor
It is very handy if you can type the command in your favorite editor. To do this in psql, you \e command. After issuing the command, psql will open the text editor defined by your EDITOR environment variable and place the most recent command that you entered in psql into the editor.
After you type the command in the editor, save it, and close the editor, psql will execute the command and return the result.
It is more useful when you edit a function in the editor.
16) Switch output options
psql supports some types of output format and allows you to customize how the output is formatted on the fly.
- \a command switches from aligned to non-aligned column output.
- \H command formats the output to HTML format.
17) Quit psql
To quit psql, you use \q command and press enter to exit psql.
In this tutorial, you have learned how to use psql commands to perform various commonly used tasks in PostgreSQL.
Источник
psql — Unix, Linux Command
SYNOPSIS
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. 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.
OPTIONS
Tag | Description |
---|---|
-a —echo-all | Print all input lines to standard output 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. |
-A —no-align | Switches to unaligned output mode. (The default output mode is otherwise aligned.) |
-c command —command command | |
Specifies that psql is to execute one command string, command, and then exit. This is useful in shell scripts. |
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. To achieve that, you could pipe the string into psql, like this: echo «\x \\ select * from foo;» | psql.
If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psqls standard input.
—dbname dbname
—echo-queries
—echo-hidden
—file filename
If filename is — (hyphen), then standard input is read.
Using this option is subtly different from writing psql . For example,
At the prompt, the user may 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.
Whenever a command is executed, psql also polls for asynchronous notification events generated by LISTEN [listen(7)] and NOTIFY [notify(7)].
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 help make psql more useful 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 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), \digits (octal), and \xdigits (hexadecimal).
If an unquoted argument begins with a colon (:), it is taken as a psql variable and the value of the variable is used as the argument instead.
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.
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 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 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.
The following meta-commands are defined:
Tag | Description | ||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\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. | ||||||||||||||||||||||||||||||||
\cd [ directory ] | |||||||||||||||||||||||||||||||||
Changes the current working directory to directory. Without argument, changes to the current users home directory. Tip: To print your current working directory, use \! pwd. | |||||||||||||||||||||||||||||||||
\C [ title ] | |||||||||||||||||||||||||||||||||
Sets 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 user name, 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 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. | |||||||||||||||||||||||||||||||||
\copy table | |||||||||||||||||||||||||||||||||
Performs a frontend (client) copy. This is an operation that runs an SQL COPY [copy(7)] 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. 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 COPY [copy(7)] command. 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. \copy table from stdin | stdout reads/writes based on the command input and output respectively. All rows are read from the same source that issued the command, continuing until \. is read or the stream reaches EOF. Output is sent to the same place as command output. To read/write from psqls standard input or output, use pstdin or pstdout. This option is useful for populating tables in-line within a SQL script file. Tip: This operation is not as efficient as the SQL COPY command because all data must pass through the client/server connection. For large amounts of data the SQL command may be preferable. | |||||||||||||||||||||||||||||||||
\copyright | |||||||||||||||||||||||||||||||||
Shows the copyright and distribution terms of PostgreSQL. | |||||||||||||||||||||||||||||||||
\d [ pattern ] \d+ [ pattern ] | |||||||||||||||||||||||||||||||||
For each relation (table, view, index, or sequence) matching the pattern, show all columns, their types, the tablespace (if not the default) 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, 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. Note: If \d is used without a pattern argument, 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 is specified, only aggregates whose names match the pattern are shown. | |||||||||||||||||||||||||||||||||
\db [ pattern ] \db+ [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all available tablespaces. If pattern is specified, only tablespaces whose names match the pattern are shown. If + is appended to the command name, each object is listed with its associated permissions. | |||||||||||||||||||||||||||||||||
\dc [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all available conversions between character-set encodings. If pattern is specified, only conversions whose names match the pattern are listed. | |||||||||||||||||||||||||||||||||
\dC | Lists all available type casts. | ||||||||||||||||||||||||||||||||
\dd [ pattern ] | |||||||||||||||||||||||||||||||||
Shows the descriptions of objects matching the pattern, 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: Descriptions for objects can be created with the COMMENT [comment(7)] SQL command. | |||||||||||||||||||||||||||||||||
\dD [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all available domains. If pattern is specified, only matching domains are shown. | |||||||||||||||||||||||||||||||||
\df [ pattern ] \df+ [ pattern ] | |||||||||||||||||||||||||||||||||
Lists available functions, together with their argument and return types. If pattern is specified, only functions whose names match the pattern are shown. If the form \df+ is used, additional information about each function, including language and description, is shown. To look up functions taking argument or returning values of a specific type, use your pagers search capability to scroll through the \df output. To reduce clutter, \df does not show data type I/O functions. This is implemented by ignoring functions that accept or return type cstring. | |||||||||||||||||||||||||||||||||
\dg [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all database roles. If pattern is specified, only those roles whose names match the pattern are listed. (This command is now effectively the same as \du.) | |||||||||||||||||||||||||||||||||
\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 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 pattern is specified, only objects whose names match the pattern are listed. | |||||||||||||||||||||||||||||||||
\dl | This is an alias for \lo_list, which shows a list of large objects. | ||||||||||||||||||||||||||||||||
\dn [ pattern ] \dn+ [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all available schemas (namespaces). If pattern (a regular expression) is specified, only schemas whose names match the pattern are listed. Non-local temporary schemas are suppressed. If + is appended to the command name, each object is listed with its associated permissions and description, if any. | |||||||||||||||||||||||||||||||||
\do [ pattern ] | |||||||||||||||||||||||||||||||||
Lists available operators with their operand and return types. If pattern is specified, only operators whose names match the pattern are listed. | |||||||||||||||||||||||||||||||||
\dp [ pattern ] | |||||||||||||||||||||||||||||||||
Produces a list of all available tables, views and sequences with their associated access privileges. If pattern is specified, only tables, views and sequences whose names match the pattern are listed. The commands GRANT and REVOKE are used to set access privileges. See GRANT [grant(7)] for more information. | |||||||||||||||||||||||||||||||||
\dT [ pattern ] \dT+ [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all data types or only those that match pattern. The command form \dT+ shows extra information. | |||||||||||||||||||||||||||||||||
\du [ pattern ] | |||||||||||||||||||||||||||||||||
Lists all database roles, 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 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. 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, vi is used on Unix systems, notepad.exe on Windows systems. | |||||||||||||||||||||||||||||||||
\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: 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 wish to use \qecho instead of this command. | |||||||||||||||||||||||||||||||||
\encoding [ encoding ] | |||||||||||||||||||||||||||||||||
Sets the client character set encoding. Without an argument, this command shows the current encoding. | |||||||||||||||||||||||||||||||||
\f [ string ] | |||||||||||||||||||||||||||||||||
Sets the field separator for unaligned query output. The default is the vertical bar (|). See also \pset for a generic way of setting output options. | |||||||||||||||||||||||||||||||||
\g [ < filename | |command > ] | |||||||||||||||||||||||||||||||||
Sends the current query input buffer to the server and optionally stores the querys output in filename or pipes the output into a separate Unix shell executing 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 ] | |||||||||||||||||||||||||||||||||
Gives 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) \l+ (or \list+) | |||||||||||||||||||||||||||||||||
List the names, owners, and character set encodings of all the databases in the server. If + is appended to the command name, database descriptions are also displayed. | |||||||||||||||||||||||||||||||||
\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 servers file system. Tip: Use \lo_list to find out the large objects OID. | |||||||||||||||||||||||||||||||||
\lo_import filename [ comment ] | |||||||||||||||||||||||||||||||||
Stores the file into a PostgreSQL large object. Optionally, it associates the given comment with the object. Example: 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 servers 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. | ||||||||||||||||||||||||||||||||
\lo_unlink loid | |||||||||||||||||||||||||||||||||
Deletes the large object with OID loid from the database. Tip: Use \lo_list to find out the large objects OID. | |||||||||||||||||||||||||||||||||
\o [ <filename | |command> ] | |||||||||||||||||||||||||||||||||
Saves future query results to the file filename or pipes future results into a separate Unix shell to execute command. If no arguments are specified, the query output will be reset to the standard output. 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. 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 thereon. Adjustable printing options are:
| |||||||||||||||||||||||||||||||||
Tip: There are various shortcut commands for \pset. See \a, \C, \H, \t, \T, and \x. Note: It is an error to call \pset without arguments. In the future this call might show the current status of all printing options. | |||||||||||||||||||||||||||||||||
\q | Quits the psql program. | ||||||||||||||||||||||||||||||||
\qecho text [ . ] | |||||||||||||||||||||||||||||||||
This command is identical to \echo except that the 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. This option is only available if psql is configured to use the GNU Readline library. | |||||||||||||||||||||||||||||||||
\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 Variables [psql(1)] below for details. Variable names are case-sensitive. Although you are welcome to set any variable to anything you want, psql treats several variables as special. They are documented in the section about variables. Note: This command is totally separate from the SQL command SET [set(7)]. | |||||||||||||||||||||||||||||||||
\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 attributes to be placed within the table tag in HTML tabular output mode. This command is equivalent to \pset tableattr table_options. | |||||||||||||||||||||||||||||||||
\timing | Toggles a display of how long each SQL statement takes, in milliseconds. | ||||||||||||||||||||||||||||||||
\w <filename | |command> | |||||||||||||||||||||||||||||||||
Outputs the current query buffer to the file filename or pipes it to the Unix command command. | |||||||||||||||||||||||||||||||||
\x | Toggles expanded table formatting mode. As such it is equivalent to \pset expanded. | ||||||||||||||||||||||||||||||||
\z [ pattern ] | |||||||||||||||||||||||||||||||||
Produces a list of all available 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. The commands GRANT and REVOKE are used to set access privileges. See GRANT [grant(7)] for more information. This is an alias for \dp (display privileges). | |||||||||||||||||||||||||||||||||
\! [ command ] | |||||||||||||||||||||||||||||||||
Escapes to a separate Unix shell or executes the Unix command command. The arguments are not further interpreted, the shell will see them as is. | |||||||||||||||||||||||||||||||||
\? | Shows help information about the backslash commands. |
The various \d commands accept a pattern parameter to specify the object name(s) to be displayed. * means any sequence of characters and ? means any single character. (This notation is comparable to Unix shell file name patterns.) Advanced users can also use regular-expression notations such as character classes, for example 7 to match any digit. To make any of these pattern-matching characters be interpreted literally, surround it with double quotes.
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.
Whenever the pattern 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 *.*.
ADVANCED FEATURES
VARIABLES
psql provides variable substitution features similar to common Unix command shells. Variables are simply name/value pairs, where the value can be any string of any length. To set variables, use the psql meta-command \set:
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:
Note: The arguments of \set 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.
If you call \set without a second argument, the variable is set, with an empty string as value. To unset (or delete) a variable, use the command \unset.
psqls internal variable names can consist of letters, numbers, and underscores in any order and any number of them. A number of these variables are treated specially by psql. 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 using such variable names for your own purposes. A list of all specially treated variables follows.
Tag | Description |
---|---|
AUTOCOMMIT | |
When on (the default), each SQL command is automatically committed upon successful completion. To postpone commit in this mode, you must enter a BEGIN or START TRANSACTION SQL command. When off or unset, SQL commands are not committed until you explicitly issue COMMIT or END. The autocommit-off mode works by issuing an implicit BEGIN for you, just before any command that is not already in a transaction block and is not itself a BEGIN or other transaction-control command, nor a command that cannot be executed inside a transaction block (such as VACUUM). Note: In autocommit-off mode, you must explicitly abandon any failed transaction by entering ABORT or ROLLBACK. Also keep in mind that if you exit the session without committing, your work will be lost. Note: The autocommit-on mode is PostgreSQLs traditional behavior, but autocommit-off is closer to the SQL spec. If you prefer autocommit-off, you may wish to set it in the system-wide psqlrc file or your | |
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 unset. |
ECHO | If set to all, all lines entered from the keyboard or from a script are written to the standard output before they are parsed or executed. To select this behavior on program start-up, use the switch -a. If set to queries, psql merely prints all queries as they are sent to the server. The switch for this is -e. |
ECHO_HIDDEN | |
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. (To select this behavior on program start-up, use the switch -E.) If you set the variable to the value noexec, the queries are just shown but are not actually sent to the server and executed. | |
ENCODING | |
The current client character set encoding. | |
HISTCONTROL | |
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. Note: This feature was shamelessly plagiarized from Bash. | |
HISTFILE | |
The file name that will be used to store the history list. The default value is /.psql_history. For example, putting /.psqlrc will cause psql to maintain a separate history for each database. Note: This feature was shamelessly plagiarized from Bash. | |
HISTSIZE | |
The number of commands to store in the command history. The default value is 500. Note: This feature was shamelessly plagiarized from Bash. | |
HOST | 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. |
IGNOREEOF | |
If unset, sending an EOF character (usually Control+D) to an interactive session of psql 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. Note: This feature was shamelessly plagiarized from Bash. | |
LASTOID | |
The value of the last affected OID, as returned from an INSERT or lo_insert command. This variable is only guaranteed to be valid until after the result of the next SQL command has been displayed. | |
ON_ERROR_ROLLBACK | |
When on, if a statement in a transaction block generates an error, the error is ignored and the transaction continues. When interactive, such errors are only ignored in interactive sessions, and not when reading script files. When off (the default), a statement in a transaction block that generates an error aborts the entire transaction. The on_error_rollback-on mode works by issuing an implicit SAVEPOINT for you, just before each command that is in a transaction block, and rolls back to the savepoint on error. | |
ON_ERROR_STOP | |
By default, if non-interactive scripts encounter an error, such as a malformed SQL command or internal meta-command, processing continues. This has been the traditional behavior of psql 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 psql session but rather using the -f option, psql will return error code 3, to distinguish this case from fatal error conditions (error code 1). | |
PORT | 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. |
PROMPT1 PROMPT2 PROMPT3 | |
These specify what the prompts psql issues should look like. See Prompting [psql(1)] below. | |
QUIET | This variable is equivalent to the command line option -q. It is probably not too useful in interactive mode. |
SINGLELINE | |
This variable is equivalent to the command line option -S. | |
SINGLESTEP | |
This variable is equivalent to the command line option -s. | |
USER | 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. |
VERBOSITY | |
This variable can be set to the values default, verbose, or terse to control the verbosity of error reports. |
SQL INTERPOLATION
An additional useful feature of psql 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 (:).
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.
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 table column. First load the file into a variable and then proceed as above.
One possible problem with this approach is that my_file.txt might contain single quotes. These need to be escaped so that they dont cause a syntax error when the second line is processed. This could be done with the program sed:
Observe the correct number of backslashes (6)! It works this way: After psql has parsed this line, it passes sed -e «s//\\#146;/g»
(tilde) if the database is your default database.
results in a boldfaced (1;) yellow-on-black (33;40) prompt on VT100-compatible, color-capable terminals.
COMMAND-LINE EDITING
psql supports the Readline library for convenient line editing and retrieval. The command history is automatically saved when psql exits and is reloaded when psql starts up. Tab-completion is also supported, although the completion logic makes no claim to be an SQL parser. If for some reason you do not like the tab completion, you can turn it off by putting this in a file named .inputrc in your home directory:
(This is not a psql but a Readline feature. Read its documentation for further details.)
ENVIRONMENT
Tag | Description |
---|---|
PAGER | 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 \pset command. |
PGDATABASE | |
Default connection database | |
PGHOST PGPORT PGUSER | Default connection parameters |
PSQL_EDITOR EDITOR VISUAL | |
Editor used by the \e command. The variables are examined in the order listed; the first that is set is used. | |
SHELL | Command executed by the \! command. |
TMPDIR | Directory for storing temporary files. The default is /tmp. |
FILES
Tag | Description |
---|---|
o | Before starting up, psql attempts to read and execute commands from the system-wide psqlrc file and the users /.psqlrc file. (On Windows, the users startup file is named %APPDATA%\postgresql\psqlrc.conf.) See PREFIX/share/psqlrc.sample for information on setting up the system-wide file. It could be used to set up the client or the server to taste (using the \set and SET commands). |
o | Both the system-wide psqlrc file and the users /.psqlrc file can be made version-specific by appending a dash and the PostgreSQL release number, for example /.psqlrc-8.1.22. A matching version-specific file will be read in preference to a non-version-specific file. |
o | The command-line history is stored in the file /.psql_history, or %APPDATA%\postgresql\psql_history on Windows. |
NOTES
Tag | Description |
---|---|
o | In an earlier life psql 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 we are not going to explain the details here as this use is discouraged. If you get strange messages, keep this in mind. For example |
which is perhaps not what one would expect.
NOTES FOR WINDOWS USERS
psql is built as a console application. Since the Windows console windows use a different encoding than the rest of the system, you must take special care when using 8-bit characters within psql. If psql detects a problematic console code page, it will warn you at startup. To change the console code page, two things are necessary:
Tag | Description |
---|---|
o | 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. |
o | Set the console font to Lucida Console, because the raster font does not work with the ANSI code page. |
EXAMPLES
The first example shows how to spread a command over several lines of input. Notice the changing prompt:
Now look at the table definition again:
Now we change the prompt to something more interesting:
Lets assume you have filled the table with data and want to take a look at it:
You can display tables in different ways by using the \pset command:
Источник