客户端命令
💥本文章相关postgreSQL版本14.4
psql 命令
- 执行
psql -?
或者psql --help
命令可以获取运行 psql 工具的帮助:
psql is the PostgreSQL interactive terminal.
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-d, --dbname=DBNAME database name to connect to (default: "root")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
(e.g., -v ON_ERROR_STOP=1)
-V, --version output version information, then exit
-X, --no-psqlrc do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute as a single transaction (if non-interactive)
-?, --help[=options] show this help, then exit
--help=commands list backslash commands, then exit
--help=variables list special variables, then exit
Input and output options:
-a, --echo-all echo all input from script
-b, --echo-errors echo failed commands
-e, --echo-queries echo commands sent to server
-E, --echo-hidden display queries that internal commands generate
-L, --log-file=FILENAME send session log to file
-n, --no-readline disable enhanced command line editing (readline)
-o, --output=FILENAME send query results to file (or |pipe)
-q, --quiet run quietly (no messages, only query output)
-s, --single-step single-step mode (confirm each query)
-S, --single-line single-line mode (end of line terminates SQL command)
Output format options:
-A, --no-align unaligned table output mode
--csv CSV (Comma-Separated Values) table output mode
-F, --field-separator=STRING
field separator for unaligned output (default: "|")
-H, --html HTML table output mode
-P, --pset=VAR[=ARG] set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
record separator for unaligned output (default: newline)
-t, --tuples-only print rows only
-T, --table-attr=TEXT set HTML table tag attributes (e.g., width, border)
-x, --expanded turn on expanded table output
-z, --field-separator-zero
set field separator for unaligned output to zero byte
-0, --record-separator-zero
set record separator for unaligned output to zero byte
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "local socket")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "root")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.
Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>
属性详解
- 基本用法
- DBNAME:要连接的数据库名称。如果省略,默认数据库是postgres。
- USERNAME:连接数据库的用户名。如果省略,默认用户是postgres。
psql [OPTION]... [DBNAME [USERNAME]]
-
通用选项
- -c, –command=COMMAND:只运行指定的SQL或内部命令,然后退出。
- -d, –dbname=DBNAME:指定要连接的数据库名称。
- -f, –file=FILENAME:从文件中执行命令,然后退出。
- -l, –list:列出所有可用的数据库,然后退出。
- -v, –set=, –variable=NAME=VALUE:设置psql变量NAME的值为VALUE。
- -V, –version:显示版本信息,然后退出。
- -X, –no-psqlrc:不读取启动文件(~/.psqlrc)。
- -1 (“one”), –single-transaction:如果非交互式,则执行作为一个单一的事务。
- -?, –help[=options]:显示帮助信息,然后退出。
- –help=commands:列出反斜杠命令,然后退出。
- –help=variables:列出特殊变量,然后退出。
-
输入和输出选项
- -A, –no-align:未对齐的表输出模式。
- –csv:CSV(逗号分隔值)表输出模式。
- -F, –field-separator=STRING:未对齐输出的字段分隔符(默认:“|”)。
- -H, –html:HTML表输出模式。
- -P, –pset=VAR[=ARG]:设置打印选项VAR为ARG(请参阅\pset命令)。
- -R, –record-separator=STRING:未对齐输出的记录分隔符(默认:换行符)。
- -t, –tuples-only:仅打印行。
- -T, –table-attr=TEXT:设置HTML表标签属性(例如,宽度,边框)。
- -x, –expanded:开启扩展表输出。
- -z, –field-separator-zero:设置未对齐输出的字段分隔符为零字节。
- -0, –record-separator-zero:设置未对齐输出的记录分隔符为零字节。
-
连接选项
- -h, –host=HOSTNAME:数据库服务器的主机名或套接字目录。
- -p, –port=PORT:数据库服务器的端口。
- -U, –username=USERNAME:数据库用户名。
- -w, –no-password:从不提示密码。
- -W, –password:强制密码提示(应该自动发生)。
使用示例
- 连接到默认数据库和用户
- 这将连接到默认数据库(通常是postgres)和默认用户(通常是postgres)。
$ psql
- 连接到特定数据库和用户
- 这将连接到名为mydatabase的数据库,并使用用户username登录。
$ psql -d mydatabase -U username
- 执行单个命令
- 这将连接到名为mydatabase的数据库,使用用户username登录,并执行一个SQL查询。
$ psql -d mydatabase -U username -c "SELECT * FROM mytable;"
- 执行多个命令
- 这将连接到名为mydatabase的数据库,使用用户username登录,并从文件myscript.sql中执行多个SQL命令。
$ psql -d mydatabase -U username -f myscript.sql
- 列出所有数据库
- 这将列出所有可用的数据库,然后退出。
$ psql -U postgres -l
- 设置变量
- 这将连接到名为mydatabase的数据库,使用用户username登录,并设置psql变量ON_ERROR_STOP的值为1。
$ psql -d mydatabase -U username -v ON_ERROR_STOP=1
- 安静模式
- 这将连接到名为mydatabase的数据库,使用用户username登录,并以安静模式运行(不显示消息,只显示查询输出)。
$ psql -d mydatabase -U username -q
- 单步模式
- 这将连接到名为mydatabase的数据库,使用用户username登录,并以单步模式运行(每次执行查询时都会提示确认)。
$ psql -d mydatabase -U username -s
- 单行模式
- 这将连接到名为mydatabase的数据库,使用用户username登录,并以单行模式运行(换行符终止SQL命令)。
$ psql -d mydatabase -U username -S
元命令
- 在PostgreSQL的命令行工具psql中,元命令是指以反斜线(\)开头的命令,它们允许用户更高效、便捷地管理数据库。(通过
\?
查看使用文档)
—————- 元命令 —————- | 说明 |
---|---|
\? 或 \help | 当你不确定某个元命令的具体用法时,可以使用\?或\help命令来获取帮助信息 |
\l 或 \list | 当你需要列出所有可用的数据库时,可以使用这个命令 |
\encoding | 查看或设置字符集编码,这对于确保数据在不同字符集之间正确转换很重要 |
\password [username] | 用于修改用户密码,这对于数据库的安全性至关重要 |
\x | 以列显示的开关,执行一次为打开,再执行一次为关闭,这对于查看大量数据时调整显示方式很有用 |
\timing on/off | 设置是否显示执行时长,这对于监控查询性能很有帮助 |
\set AUTOCOMMIT on/off | 打开或关闭自动提交功能,这对于控制事务的提交很有用 |
\conninfo | 显示连接信息,这对于诊断连接问题很有帮助 |
! [command] | 执行shell命令,这对于需要与外部工具交互的情况很有用 |
\i filename | 执行指定文件中的SQL语句,这对于批量执行SQL脚本很有用 |
\d | 查看当前数据库下的所有表、视图和序列,这对于快速了解数据库结构很有用 |
\dt | 只查看数据库中的所有表,这对于快速访问特定类型的数据库对象很有用 |
\du | 查看数据库角色信息,这对于管理数据库角色很有用 |
\db | 查看表空间列表,这对于管理数据库存储很有用 |
\gexec | 将当前查询缓冲区发送到服务器,然后将查询输出(如果有的话)的每一行的每一列都要作为要执行的SQL语句处理,这对于自动化执行SQL语句很有用 |
连接数据库
- 使用 postgres 用户连接到本机 127.0.0.1 端口 5432 的 shoping 数据库。
$ psql -h localhost -p 5432 -U postgres -d shoping -W
- 使用字符串或URI连接。
$ psql "host=localhost user=postgres password=123456 port=5432 dbname=shoping"
$ psql postgresql://localhost:5432/shoping?user=postgres
—————- 连接元命令 —————- | 说明 |
---|---|
\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo} |
连接新数据库(当前为“postgres”) |
\conninfo |
显示当前连接信息 |
\encoding [ENCODING] |
显示或设置客户端编码 |
\password [USERNAME] |
安全修改用户密码 |
查看当前连接信息
- 成功建立连接之后,可以使用元命令
\conninfo
查看当前连接信息。 - 当你需要了解当前连接的详细信息,比如数据库名称、用户名、主机和端口等,可以使用这个命令。
postgres=# \conninfo
You are connected to database "shoping" as user "postgres" on host "localhost" (address "::1") at port "5432".
切换数据库连接
\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
-
使用元命令\c可以重新连接数据库:
- 连接到新的数据库。你可以指定数据库名称(DBNAME)、用户名(USER)、主机(HOST)、端口(PORT)或者使用conninfo参数显示当前连接信息。
- 如果你想要连接到一个新的数据库,或者想要查看当前连接的详细信息,可以使用这个命令。
-
连接到默认数据库(这将连接到默认数据库)。
postgres=# \c
You are now connected to database "postgres" as user "postgres".
- 连接到特定数据库(这将连接到名为mydatabase的数据库)。
shoping=# \c postgres
You are now connected to database "postgres" as user "postgres".
- 切换用户 tony。
postgres=# \c - tony
Password for user tony:
查看/设置客户端编码
- 通过
\encoding [ENCODING]
命令可以查看或者设置客户端的编码格式。例如: - 查看客户端编码:
postgres=# \encoding
UTF8
- 设置和护短编码:
postgres=# \encoding gbk
postgres=# \encoding
GBK
修改用户密码
- 使用
\password [username]
命令可以安全地修改指定用户的密码,默认为修改当前用户密码。例如:
postgres=# \password tony
Enter new password for user "tony":
Enter it again:
查看帮助
- psql 提供了关于该工具的命令、选项、变量配置以及 SQL 语句的帮助信息。
帮助元命令 | 说明 |
---|---|
\? [commands] |
显示反斜杠commands的帮助 |
\? options |
显示关于PSQL命令行选项的帮助 |
\? variables |
显示对特殊变量的帮助 |
\h [NAME] |
SQL命令的语法帮助,*表示所有命令 |
psql 命令帮助
- 使用
\?
或者\? commands
命令可以获得所有反斜线命令的帮助。- 该命令的结果和
psql --help=commands
的输出相同。
- 该命令的结果和
postgres=# \?
General
\copyright show PostgreSQL usage and distribution terms
\crosstabview [COLUMNS] execute query and display results in crosstab
\errverbose show most recent error message at maximum verbosity
\g [(OPTIONS)] [FILE] execute query (and send results to file or |pipe);
\g with no arguments is equivalent to a semicolon
\gdesc describe result of query, without executing it
\gexec execute query, then execute each value in its result
\gset [PREFIX] execute query and store results in psql variables
\gx [(OPTIONS)] [FILE] as \g, but forces expanded output mode
\q quit psql
\watch [SEC] execute query every SEC seconds
Help
\? [commands] show help on backslash commands
\? options show help on psql command-line options
\? variables show help on special variables
\h [NAME] help on syntax of SQL commands, * for all commands
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
Input/Output
\copy ... perform SQL COPY with data stream to the client host
\echo [-n] [STRING] write string to standard output (-n for no newline)
\i FILE execute commands from file
\ir FILE as \i, but relative to location of current script
\o [FILE] send all query results to file or |pipe
\qecho [-n] [STRING] write string to \o output stream (-n for no newline)
\warn [-n] [STRING] write string to standard error (-n for no newline)
Conditional
\if EXPR begin conditional block
\elif EXPR alternative within current conditional block
\else final alternative within current conditional block
\endif end conditional block
Informational
(options: S = show system objects, + = additional detail)
\d[S+] list tables, views, and sequences
\d[S+] NAME describe table, view, sequence, or index
\da[S] [PATTERN] list aggregates
\dA[+] [PATTERN] list access methods
\dAc[+] [AMPTRN [TYPEPTRN]] list operator classes
\dAf[+] [AMPTRN [TYPEPTRN]] list operator families
\dAo[+] [AMPTRN [OPFPTRN]] list operators of operator families
\dAp[+] [AMPTRN [OPFPTRN]] list support functions of operator families
\db[+] [PATTERN] list tablespaces
\dc[S+] [PATTERN] list conversions
\dC[+] [PATTERN] list casts
\dd[S] [PATTERN] show object descriptions not displayed elsewhere
\dD[S+] [PATTERN] list domains
\ddp [PATTERN] list default privileges
\dE[S+] [PATTERN] list foreign tables
\des[+] [PATTERN] list foreign servers
\det[+] [PATTERN] list foreign tables
\deu[+] [PATTERN] list user mappings
\dew[+] [PATTERN] list foreign-data wrappers
\df[anptw][S+] [FUNCPTRN [TYPEPTRN ...]]
list [only agg/normal/procedure/trigger/window] functions
\dF[+] [PATTERN] list text search configurations
\dFd[+] [PATTERN] list text search dictionaries
\dFp[+] [PATTERN] list text search parsers
\dFt[+] [PATTERN] list text search templates
\dg[S+] [PATTERN] list roles
\di[S+] [PATTERN] list indexes
\dl list large objects, same as \lo_list
\dL[S+] [PATTERN] list procedural languages
\dm[S+] [PATTERN] list materialized views
\dn[S+] [PATTERN] list schemas
\do[S+] [OPPTRN [TYPEPTRN [TYPEPTRN]]]
list operators
\dO[S+] [PATTERN] list collations
\dp [PATTERN] list table, view, and sequence access privileges
\dP[itn+] [PATTERN] list [only index/table] partitioned relations [n=nested]
\drds [ROLEPTRN [DBPTRN]] list per-database role settings
\dRp[+] [PATTERN] list replication publications
\dRs[+] [PATTERN] list replication subscriptions
\ds[S+] [PATTERN] list sequences
\dt[S+] [PATTERN] list tables
\dT[S+] [PATTERN] list data types
\du[S+] [PATTERN] list roles
\dv[S+] [PATTERN] list views
\dx[+] [PATTERN] list extensions
\dX [PATTERN] list extended statistics
\dy[+] [PATTERN] list event triggers
\l[+] [PATTERN] list databases
\sf[+] FUNCNAME show a function's definition
\sv[+] VIEWNAME show a view's definition
\z [PATTERN] same as \dp
Formatting
\a toggle between unaligned and aligned output mode
\C [STRING] set table title, or unset if none
\f [STRING] show or set field separator for unaligned query output
\H toggle HTML output mode (currently off)
\pset [NAME [VALUE]] set table output option
(border|columns|csv_fieldsep|expanded|fieldsep|
fieldsep_zero|footer|format|linestyle|null|
numericlocale|pager|pager_min_lines|recordsep|
recordsep_zero|tableattr|title|tuples_only|
unicode_border_linestyle|unicode_column_linestyle|
unicode_header_linestyle)
\t [on|off] show only rows (currently off)
\T [STRING] set HTML <table> tag attributes, or unset if none
\x [on|off|auto] toggle expanded output (currently off)
Connection
\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
connect to new database (currently "postgres")
\conninfo display information about current connection
\encoding [ENCODING] show or set client encoding
\password [USERNAME] securely change the password for a user
Operating System
\cd [DIR] change the current working directory
\setenv NAME [VALUE] set or unset environment variable
\timing [on|off] toggle timing of commands (currently off)
\! [COMMAND] execute command in shell or start interactive shell
Variables
\prompt [TEXT] NAME prompt user to set internal variable
\set [NAME [VALUE]] set internal variable, or list all if no parameters
\unset NAME unset (delete) internal variable
Large Objects
\lo_export LOBOID FILE
\lo_import FILE [COMMENT]
\lo_list
\lo_unlink LOBOID large object operations
psql 命令行选项帮助
- 输入
\? options
命令可以获得运行 psql 时的命令行选项相关的帮助:- 该命令的结果和上文中的
psql -?
或者psql --help
的输出相同。
- 该命令的结果和上文中的
postgres=# \? options
psql is the PostgreSQL interactive terminal.
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-d, --dbname=DBNAME database name to connect to (default: "root")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
(e.g., -v ON_ERROR_STOP=1)
-V, --version output version information, then exit
-X, --no-psqlrc do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute as a single transaction (if non-interactive)
-?, --help[=options] show this help, then exit
--help=commands list backslash commands, then exit
--help=variables list special variables, then exit
Input and output options:
-a, --echo-all echo all input from script
-b, --echo-errors echo failed commands
-e, --echo-queries echo commands sent to server
-E, --echo-hidden display queries that internal commands generate
-L, --log-file=FILENAME send session log to file
-n, --no-readline disable enhanced command line editing (readline)
-o, --output=FILENAME send query results to file (or |pipe)
-q, --quiet run quietly (no messages, only query output)
-s, --single-step single-step mode (confirm each query)
-S, --single-line single-line mode (end of line terminates SQL command)
Output format options:
-A, --no-align unaligned table output mode
--csv CSV (Comma-Separated Values) table output mode
-F, --field-separator=STRING
field separator for unaligned output (default: "|")
-H, --html HTML table output mode
-P, --pset=VAR[=ARG] set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
record separator for unaligned output (default: newline)
-t, --tuples-only print rows only
-T, --table-attr=TEXT set HTML table tag attributes (e.g., width, border)
-x, --expanded turn on expanded table output
-z, --field-separator-zero
set field separator for unaligned output to zero byte
-0, --record-separator-zero
set record separator for unaligned output to zero byte
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "local socket")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "root")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.
Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>
psql 配置变量帮助
- 输入
\? variables
命令可以获得 psql 的配置变量、环境变量以及显示设置相关的帮助信息:- 该命令的结果和
psql --help=variables
的输出相同。
- 该命令的结果和
postgres=# \? variables
List of specially treated variables
psql variables:
Usage:
psql --set=NAME=VALUE
or \set NAME VALUE inside psql
AUTOCOMMIT
if set, successful SQL commands are automatically committed
COMP_KEYWORD_CASE
determines the case used to complete SQL key words
[lower, upper, preserve-lower, preserve-upper]
DBNAME
the currently connected database name
ECHO
controls what input is written to standard output
[all, errors, none, queries]
ECHO_HIDDEN
if set, display internal queries executed by backslash commands;
if set to "noexec", just show them without execution
ENCODING
current client character set encoding
ERROR
true if last query failed, else false
FETCH_COUNT
the number of result rows to fetch and display at a time (0 = unlimited)
HIDE_TABLEAM
if set, table access methods are not displayed
HIDE_TOAST_COMPRESSION
if set, compression methods are not displayed
HISTCONTROL
controls command history [ignorespace, ignoredups, ignoreboth]
HISTFILE
file name used to store the command history
HISTSIZE
maximum number of commands to store in the command history
HOST
the currently connected database server host
IGNOREEOF
number of EOFs needed to terminate an interactive session
LASTOID
value of the last affected OID
LAST_ERROR_MESSAGE
LAST_ERROR_SQLSTATE
message and SQLSTATE of last error, or empty string and "00000" if none
ON_ERROR_ROLLBACK
if set, an error doesn't stop a transaction (uses implicit savepoints)
ON_ERROR_STOP
stop batch execution after error
PORT
server port of the current connection
PROMPT1
specifies the standard psql prompt
PROMPT2
specifies the prompt used when a statement continues from a previous line
PROMPT3
specifies the prompt used during COPY ... FROM STDIN
QUIET
run quietly (same as -q option)
ROW_COUNT
number of rows returned or affected by last query, or 0
SERVER_VERSION_NAME
SERVER_VERSION_NUM
server's version (in short string or numeric format)
SHOW_CONTEXT
controls display of message context fields [never, errors, always]
SINGLELINE
if set, end of line terminates SQL commands (same as -S option)
SINGLESTEP
single-step mode (same as -s option)
SQLSTATE
SQLSTATE of last query, or "00000" if no error
USER
the currently connected database user
VERBOSITY
controls verbosity of error reports [default, verbose, terse, sqlstate]
VERSION
VERSION_NAME
VERSION_NUM
psql's version (in verbose string, short string, or numeric format)
Display settings:
Usage:
psql --pset=NAME[=VALUE]
or \pset NAME [VALUE] inside psql
border
border style (number)
columns
target width for the wrapped format
expanded (or x)
expanded output [on, off, auto]
fieldsep
field separator for unaligned output (default "|")
fieldsep_zero
set field separator for unaligned output to a zero byte
footer
enable or disable display of the table footer [on, off]
format
set output format [unaligned, aligned, wrapped, html, asciidoc, ...]
linestyle
set the border line drawing style [ascii, old-ascii, unicode]
null
set the string to be printed in place of a null value
numericlocale
enable display of a locale-specific character to separate groups of digits
pager
control when an external pager is used [yes, no, always]
recordsep
record (line) separator for unaligned output
recordsep_zero
set record separator for unaligned output to a zero byte
tableattr (or T)
specify attributes for table tag in html format, or proportional
column widths for left-aligned data types in latex-longtable format
title
set the table title for subsequently printed tables
tuples_only
if set, only actual table data is shown
unicode_border_linestyle
unicode_column_linestyle
unicode_header_linestyle
set the style of Unicode line drawing [single, double]
Environment variables:
Usage:
NAME=VALUE [NAME=VALUE] psql ...
or \setenv NAME [VALUE] inside psql
COLUMNS
number of columns for wrapped format
PGAPPNAME
same as the application_name connection parameter
PGDATABASE
same as the dbname connection parameter
PGHOST
same as the host connection parameter
PGPASSFILE
password file name
PGPASSWORD
connection password (not recommended)
PGPORT
same as the port connection parameter
PGUSER
same as the user connection parameter
PSQL_EDITOR, EDITOR, VISUAL
editor used by the \e, \ef, and \ev commands
PSQL_EDITOR_LINENUMBER_ARG
how to specify a line number when invoking the editor
PSQL_HISTORY
alternative location for the command history file
PSQL_PAGER, PAGER
name of external pager program
PSQLRC
alternative location for the user's .psqlrc file
SHELL
shell used by the \! command
TMPDIR
directory for temporary files
SQL 语句帮助
- 输入
\h [ command ]
或者\help [ command ]
命令可以获得 SQL 命令语法相关的帮助:
postgres=# \h
Available help:
ABORT CHECKPOINT CREATE USER DROP TRIGGER
ALTER AGGREGATE CLOSE CREATE USER MAPPING DROP TYPE
ALTER COLLATION CLUSTER CREATE VIEW DROP USER
ALTER CONVERSION COMMENT DEALLOCATE DROP USER MAPPING
ALTER DATABASE COMMIT DECLARE DROP VIEW
ALTER DEFAULT PRIVILEGES COMMIT PREPARED DELETE END
ALTER DOMAIN COPY DISCARD EXECUTE
ALTER EVENT TRIGGER CREATE ACCESS METHOD DO EXPLAIN
ALTER EXTENSION CREATE AGGREGATE DROP ACCESS METHOD FETCH
ALTER FOREIGN DATA WRAPPER CREATE CAST DROP AGGREGATE GRANT
ALTER FOREIGN TABLE CREATE COLLATION DROP CAST IMPORT FOREIGN SCHEMA
ALTER FUNCTION CREATE CONVERSION DROP COLLATION INSERT
ALTER GROUP CREATE DATABASE DROP CONVERSION LISTEN
ALTER INDEX CREATE DOMAIN DROP DATABASE LOAD
ALTER LANGUAGE CREATE EVENT TRIGGER DROP DOMAIN LOCK
ALTER LARGE OBJECT CREATE EXTENSION DROP EVENT TRIGGER MOVE
ALTER MATERIALIZED VIEW CREATE FOREIGN DATA WRAPPER DROP EXTENSION NOTIFY
ALTER OPERATOR CREATE FOREIGN TABLE DROP FOREIGN DATA WRAPPER PREPARE
ALTER OPERATOR CLASS CREATE FUNCTION DROP FOREIGN TABLE PREPARE TRANSACTION
ALTER OPERATOR FAMILY CREATE GROUP DROP FUNCTION REASSIGN OWNED
ALTER POLICY CREATE INDEX DROP GROUP REFRESH MATERIALIZED VIEW
ALTER PROCEDURE CREATE LANGUAGE DROP INDEX REINDEX
ALTER PUBLICATION CREATE MATERIALIZED VIEW DROP LANGUAGE RELEASE SAVEPOINT
ALTER ROLE CREATE OPERATOR DROP MATERIALIZED VIEW RESET
ALTER ROUTINE CREATE OPERATOR CLASS DROP OPERATOR REVOKE
ALTER RULE CREATE OPERATOR FAMILY DROP OPERATOR CLASS ROLLBACK
ALTER SCHEMA CREATE POLICY DROP OPERATOR FAMILY ROLLBACK PREPARED
ALTER SEQUENCE CREATE PROCEDURE DROP OWNED ROLLBACK TO SAVEPOINT
ALTER SERVER CREATE PUBLICATION DROP POLICY SAVEPOINT
ALTER STATISTICS CREATE ROLE DROP PROCEDURE SECURITY LABEL
ALTER SUBSCRIPTION CREATE RULE DROP PUBLICATION SELECT
ALTER SYSTEM CREATE SCHEMA DROP ROLE SELECT INTO
ALTER TABLE CREATE SEQUENCE DROP ROUTINE SET
ALTER TABLESPACE CREATE SERVER DROP RULE SET CONSTRAINTS
ALTER TEXT SEARCH CONFIGURATION CREATE STATISTICS DROP SCHEMA SET ROLE
ALTER TEXT SEARCH DICTIONARY CREATE SUBSCRIPTION DROP SEQUENCE SET SESSION AUTHORIZATION
ALTER TEXT SEARCH PARSER CREATE TABLE DROP SERVER SET TRANSACTION
ALTER TEXT SEARCH TEMPLATE CREATE TABLE AS DROP STATISTICS SHOW
ALTER TRIGGER CREATE TABLESPACE DROP SUBSCRIPTION START TRANSACTION
ALTER TYPE CREATE TEXT SEARCH CONFIGURATION DROP TABLE TABLE
ALTER USER CREATE TEXT SEARCH DICTIONARY DROP TABLESPACE TRUNCATE
ALTER USER MAPPING CREATE TEXT SEARCH PARSER DROP TEXT SEARCH CONFIGURATION UNLISTEN
ALTER VIEW CREATE TEXT SEARCH TEMPLATE DROP TEXT SEARCH DICTIONARY UPDATE
ANALYZE CREATE TRANSFORM DROP TEXT SEARCH PARSER VACUUM
BEGIN CREATE TRIGGER DROP TEXT SEARCH TEMPLATE VALUES
CALL CREATE TYPE DROP TRANSFORM WITH
- 直接查看某个具体 SQL 命令的语法帮助,例如:
postgres=# \h create index
Command: CREATE INDEX
Description: define a new index
Syntax:
CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] name ] ON [ ONLY ] table_name [ USING method ]
( { column_name | ( expression ) } [ COLLATE collation ] [ opclass [ ( opclass_parameter = value [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] )
[ INCLUDE ( column_name [, ...] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) ]
[ TABLESPACE tablespace_name ]
[ WHERE predicate ]
URL: https://www.postgresql.org/docs/14/sql-createindex.html
退出 psql 工具
- 退出 psql 终端的命令包括\q、\quit、quit以及exit。例如:
postgres=# \q
#
常用元命令
执行 SQL 语句
- psql 中的 SQL 命令以;或者\g结束,同时发送到服务端执行并返回结果。例如,以下查询返回了当前 PostgreSQL 数据库的版本:
postgres=# SELECT version();
version
-----------------------------------------------------------------------------------------------------------------------------
PostgreSQL 14.4 (Debian 14.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
(1 row)
保存查询结果
- 如果想要将查询结果直接保存到某个文件中,可以使用\g filename命令。例如:
- 此时,数据库的版本信息被保存到了操作系统当前工作目录下的 result.txt 文件中。
\! command
用于执行操作系统命令,这里使用 Linux 的 ls 命令查看文件列表。
postgres=# SELECT version() \g result.txt
postgres=#
postgres-# \! ls -al
total 92
drwxr-xr-x 1 root root 4096 Sep 22 21:59 .
drwxr-xr-x 1 root root 4096 Sep 22 21:59 ..
drwxr-xr-x 2 root root 4096 Aug 1 2022 bin
drwxr-xr-x 2 root root 4096 Jul 1 2022 boot
drwxr-xr-x 11 root root 3140 Sep 22 11:35 dev
drwxr-xr-x 2 root root 4096 Sep 18 20:31 docker-entrypoint-initdb.d
-rwxr-xr-x 1 root root 0 Sep 18 20:34 .dockerenv
drwxr-xr-x 1 root root 4096 Sep 18 20:34 etc
drwxr-xr-x 2 root root 4096 Jul 1 2022 home
drwxr-xr-x 1 root root 4096 Aug 1 2022 lib
drwxr-xr-x 2 root root 4096 Aug 1 2022 lib64
drwxr-xr-x 2 root root 4096 Aug 1 2022 media
drwxr-xr-x 2 root root 4096 Aug 1 2022 mnt
drwxr-xr-x 2 root root 4096 Aug 1 2022 opt
dr-xr-xr-x 219 root root 0 Sep 22 11:35 proc
-rw-r--r-- 1 root root 386 Sep 22 21:59 result.txt
drwx------ 1 root root 4096 Sep 20 20:46 root
drwxr-xr-x 1 root root 4096 Aug 2 2022 run
drwxr-xr-x 2 root root 4096 Aug 1 2022 sbin
drwxr-xr-x 2 root root 4096 Aug 1 2022 srv
dr-xr-xr-x 11 root root 0 Sep 22 11:35 sys
drwxrwxrwt 1 root root 4096 Aug 2 2022 tmp
drwxr-xr-x 1 root root 4096 Aug 1 2022 usr
drwxr-xr-x 1 root root 4096 Aug 1 2022 var
postgres=#
postgres-# \! cat result.txt
version
-----------------------------------------------------------------------------------------------------------------------------
PostgreSQL 14.4 (Debian 14.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
(1 row)
- 另外,执行\o [ filename ]命令可以将之后的所有查询结果和命令返回信息保存到指定文件,默认为标准输出。例如:
- 前两个 select 语句的结果打印到了 result.txt 文件中,然后又将查询结果定向为标准输出。
shoping=# \o result.txt
shoping=# select * from dept;
shoping=# select 1+1;
shoping=# \o
shoping=#
shoping=# \! cat result.txt
department_id | department_name
---------------+-----------------
10 | Administration
20 | Marketing
(2 rows)
?column?
----------
2
(1 row)
- 还有一个\copy …命令可以用于将表或者查询结果保存到指定文件中,或者从指定文件中读取内容到表中。例如:
shoping-# \copy dept to dept.txt
COPY 2
shoping-#
shoping-# \! cat dept.txt
10 Administration
20 Marketing
\copy
COPY table_name FROM 'file_path' [DELIMITER 'delimiter']
COPY table_name TO 'file_path' [DELIMITER 'delimiter']
COPY table_name FROM STDIN [DELIMITER 'delimiter']
COPY table_name TO STDOUT [DELIMITER 'delimiter']
重复执行语句
\watch [SEC]
命令可以用于每隔指定秒数(默认 2 秒)执行一次 SQL 语句。例如:
shoping=# SELECT now() \watch 5
Sun 22 Sep 2024 11:23:05 PM CST (every 5s)
now
-------------------------------
2024-09-22 15:23:05.777741+00
(1 row)
Sun 22 Sep 2024 11:23:10 PM CST (every 5s)
now
-------------------------------
2024-09-22 15:23:10.789936+00
(1 row)
Sun 22 Sep 2024 11:23:15 PM CST (every 5s)
now
-------------------------------
2024-09-22 15:23:15.797624+00
(1 row)
Sun 22 Sep 2024 11:23:20 PM CST (every 5s)
显示/清空查询缓冲区
- 输入
\p
命令可以显示当前缓冲区或者最近一次执行的命令:
shoping=# \p
select 1+1;
- 输入
\r
命令可以清空当前缓冲区中的内容:
shoping=# \r
Query buffer reset (cleared).
执行上一次命令
- 直接输入没有参数的
\g
命令表示再次执行查询缓冲区中的命令或者上一次执行的语句。例如:
shoping=# select * from dept;
department_id | department_name
---------------+-----------------
10 | Administration
20 | Marketing
(2 rows)
shoping=# \g
department_id | department_name
---------------+-----------------
10 | Administration
20 | Marketing
(2 rows)
查看/保存命令历史
\s [ filename ]
命令用于将历史命令保存到文件中,如果省略 filename 则显示到终端。例如:
shoping=# \s
\c
\du
CREATE ROLE admin CREATEDB CREATEROLE;
su
postgres
exit
CREATE ROLE admin CREATEDB CREATEROLE;
CREATE ROLE admin CREATEDB CREATEROLE;
\c
\c
显示语句执行时间
\timing [ on | off ]
命令可以用于显示或者关闭 SQL 语句的执行时间,单位为毫秒。例如:- 不指定参数的\timing命令可以在 on 和 off 之间切换。
shoping=# \timing on
Timing is on.
shoping=# select * from dept;
department_id | department_name
---------------+-----------------
10 | Administration
20 | Marketing
(2 rows)
Time: 0.655 ms
shoping=# \timing
Timing is off.
设置输出格式
\pset [ option [ value ] ]
命令可以用于显示或者设置与查询结果输出相关的选项。例如:(返回了当前的选项设置)
shoping=# \pset
border 1
columns 0
csv_fieldsep ','
expanded off
fieldsep '|'
fieldsep_zero off
footer on
format aligned
linestyle ascii
null ''
numericlocale off
pager 1
pager_min_lines 0
recordsep '\n'
recordsep_zero off
tableattr
title
tuples_only off
unicode_border_linestyle single
unicode_column_linestyle single
unicode_header_linestyle single
执行脚本文件
\i filename
命令用于读取文件并执行其中的命令。在操作系统当前目录中创建一个脚本文件 test.sql,输入以下语句:
查看数据库对象信息
- psql 提供了大量用于查看数据库对象信息的元命令,绝大多数以 \d 开头。其中很多命令支持额外的 S 后缀,用于显示系统对象,否则只显示当前用户拥有访问权限的对象;或者额外的 + 后缀,用于显示额外的信息。
查看角色和用户
\du[S+] [ pattern ]
或者\dg[S+] [ pattern ]
命令用于列出用户创建的角色、用户和组。例如:- 如果指定了 S 选项,同时会显示系统创建的角色;如果指定了 + 选项,还会显示额外的描述信息;如果指定了 pattern,只有名称匹配指定模式的角色才会显示。
shoping=# \duS
List of roles
Role name | Attributes | Member of
---------------------------+------------------------------------------------------------+--------------------------------------------------------------
admin | Create role, Create DB, Cannot login | {}
pg_database_owner | Cannot login | {}
pg_execute_server_program | Cannot login | {}
pg_monitor | Cannot login | {pg_read_all_settings,pg_read_all_stats,pg_stat_scan_tables}
pg_read_all_data | Cannot login | {}
pg_read_all_settings | Cannot login | {}
pg_read_all_stats | Cannot login | {}
pg_read_server_files | Cannot login | {}
pg_signal_backend | Cannot login | {}
pg_stat_scan_tables | Cannot login | {}
pg_write_all_data | Cannot login | {}
pg_write_server_files | Cannot login | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
tony | Password valid until 2025-01-01 00:00:00+00 | {}
查看数据库
\l[+] [pattern]
命令用于列出系统中的所有数据库。例如:- 如果指定 + 选项,还会显示额外的数据库大小、默认表空间和描述信息;如果指定了 pattern,只有名称匹配指定模式的数据库才会显示。
shoping=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
shoping | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +
| | | | | postgres=CTc/postgres
(4 rows)
shoping=# \l+
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description
-----------+----------+----------+------------+------------+-----------------------+---------+------------+--------------------------------------------
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | 8553 kB | pg_default | default administrative connection database
shoping | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | 8921 kB | pg_default |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +| 8401 kB | pg_default | unmodifiable empty database
| | | | | postgres=CTc/postgres | | |
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres +| 8401 kB | pg_default | default template for new databases
| | | | | postgres=CTc/postgres | | |
(4 rows)
查看模式
\dn[S+] [ pattern ]
命令用于列出当前数据库中的所有模式(schema)。例如:- 如果指定了 S 选项,同时会显示系统模式;如果指定了 + 选项,还会显示额外的授权信息和描述;如果指定了 pattern,只有名称匹配指定模式的 schema 才会显示。
shoping=# \dn
List of schemas
Name | Owner
--------+----------
public | postgres
(1 row)
shoping=# \dnS
List of schemas
Name | Owner
--------------------+----------
information_schema | postgres
pg_catalog | postgres
pg_toast | postgres
public | postgres
(4 rows)
查看表空间
\db[+] [ pattern ]
命令用于列出系统中的所有表空间。例如:- 如果指定了 + 选项,还会显示额外的选项、空间大小、授权信息和描述;如果指定了 pattern,只有名称匹配指定模式的表空间才会显示。
shoping=# \db
List of tablespaces
Name | Owner | Location
------------+----------+----------
pg_default | postgres |
pg_global | postgres |
(2 rows)
shoping=# \db+
List of tablespaces
Name | Owner | Location | Access privileges | Options | Size | Description
------------+----------+----------+-------------------+---------+--------+-------------
pg_default | postgres | | | | 33 MB |
pg_global | postgres | | | | 560 kB |
(2 rows)
查看表
\dt[S+] [ pattern ]
命令用于列出所有的数据表。例如:- 如果指定了 S 选项,同时会显示系统表;如果指定了 + 选项,还会显示额外的大小和描述信息;如果指定了 pattern,只有名称匹配指定模式的表才会显示。
- 另外,
\d[S+] [ pattern ]
命令可以同时列出表、视图、物化视图、索引、序列以及外部表的信息,等价于\dtvmsE[S+] [ pattern ]
命令。
shoping=# \dt+
List of relations
Schema | Name | Type | Owner | Persistence | Access method | Size | Description
--------+-------------+-------+----------+-------------+---------------+------------+-------------
public | departments | table | postgres | permanent | heap | 8192 bytes |
public | dept | table | postgres | permanent | heap | 8192 bytes |
public | emp | table | postgres | permanent | heap | 0 bytes |
public | employees | table | postgres | permanent | heap | 40 kB |
public | jobs | table | postgres | permanent | heap | 8192 bytes |
public | sales | table | postgres | permanent | heap | 8192 bytes |
public | tbl_char | table | postgres | permanent | heap | 8192 bytes |
(7 rows)
查看索引
\di[S+] [ pattern ]
命令用于列出所有的索引。例如:- 如果指定了 S 选项,同时会显示系统表上的索引;如果指定了 + 选项,还会显示额外的大小和描述信息;如果指定了 pattern,只有名称匹配指定模式的索引才会显示。
shoping=# \di
List of relations
Schema | Name | Type | Owner | Table
--------+-------------------+-------+----------+-------------
public | dept_id_pk | index | postgres | departments
public | dept_location_ix | index | postgres | departments
public | dept_pkey | index | postgres | dept
public | emp_department_ix | index | postgres | employees
public | emp_email_uk | index | postgres | employees
public | emp_emp_id_pk | index | postgres | employees
public | emp_job_ix | index | postgres | employees
public | emp_manager_ix | index | postgres | employees
public | emp_name_ix | index | postgres | employees
public | emp_pkey | index | postgres | emp
public | job_id_pk | index | postgres | jobs
(11 rows)
shoping=# \di+
List of relations
Schema | Name | Type | Owner | Table | Persistence | Access method | Size | Description
--------+-------------------+-------+----------+-------------+-------------+---------------+------------+-------------
public | dept_id_pk | index | postgres | departments | permanent | btree | 16 kB |
public | dept_location_ix | index | postgres | departments | permanent | btree | 16 kB |
public | dept_pkey | index | postgres | dept | permanent | btree | 16 kB |
public | emp_department_ix | index | postgres | employees | permanent | btree | 16 kB |
public | emp_email_uk | index | postgres | employees | permanent | btree | 16 kB |
public | emp_emp_id_pk | index | postgres | employees | permanent | btree | 16 kB |
public | emp_job_ix | index | postgres | employees | permanent | btree | 16 kB |
public | emp_manager_ix | index | postgres | employees | permanent | btree | 16 kB |
public | emp_name_ix | index | postgres | employees | permanent | btree | 16 kB |
public | emp_pkey | index | postgres | emp | permanent | btree | 8192 bytes |
public | job_id_pk | index | postgres | jobs | permanent | btree | 16 kB |
(11 rows)
查看序列
\ds[S+] [ pattern ]
命令用于列出所有的序列。例如:- 如果指定了 S 选项,同时会显示系统创建的序列;如果指定了 + 选项,还会显示额外的大小和描述信息;如果指定了 pattern,只有名称匹配指定模式的序列才会显示。
hrdb=> \ds
List of relations
Schema | Name | Type | Owner
--------+--------------------------+----------+-------
public | accounts_id_seq | sequence | tony
public | employees_history_id_seq | sequence | tony
public | users_id_seq | sequence | tony
(3 rows)
查看/编辑视图
\dv[S+] [ pattern ]
命令用于列出所有的视图。例如:- 如果指定了 S 选项,同时会显示系统创建的视图;如果指定了 + 选项,还会显示额外的大小和描述信息;如果指定了 pattern,只有名称匹配指定模式的视图才会显示。
shoping=# \dv
List of relations
Schema | Name | Type | Owner
--------+------------------+------+----------
public | emp_details_view | view | postgres
(1 row)
shoping=# \dv+
List of relations
Schema | Name | Type | Owner | Persistence | Size | Description
--------+------------------+------+----------+-------------+---------+-------------
public | emp_details_view | view | postgres | permanent | 0 bytes |
(1 row)
\sv[+] view_name
命令用于显示视图的定义语句。例如:- 如果指定了 + 选项,同时会显示行号(从 1 开始)。
shoping=# \sv emp_details_view
CREATE OR REPLACE VIEW public.emp_details_view AS
SELECT e.employee_id,
e.job_id,
e.manager_id,
e.department_id,
d.location_id,
e.first_name,
e.last_name,
e.salary,
e.commission_pct,
d.department_name,
j.job_title
FROM employees e,
departments d,
jobs j
WHERE e.department_id = d.department_id AND j.job_id::text = e.job_id::text