PSQL使用技巧汇集(2)

1、前言介绍

各大数据库都有自己的命令行客户端程序,也是访问后台数据库的一个基本门面:

  • Oracle: sqlplus
  • DB2: db2
  • MySQL: mysql
  • HANA: hdbsql
  • Sybase: isql
  • MSSQL: tsql
  • PostgreSQL: psql

命令行的易用和好用与否,也很大程度上的影响了用户对目标数据库的直接感受。这里我们看看咱们PGer对PostgreSQL的psql命令行的一些使用方法的总结,一个字:强! 两个字:强大!

终于整理完了。总计152个小技巧。分成两篇弄完。

2、技巧汇集

技巧0069 (\d)

\d pattern将用于显示每个关系(表、视图、物化视图、索引、序列或外部表) 或者符合条件的组合类型,它们所有的列和类型, 表空间(如果不是默认表空间),特殊属性(像NOT NULL或者default)。相关联的索引、约束、规则、触发器等也会显示出来。对于外部表,相关联的外部服务器也会一同显示。

对某些类型的关系,\d会为每一列显示附加信息:如序列对应的列值、索引对应的索引表达式、外部表的FDW选项。

始自7.1。9.0, 9.3做过更新。

1
2
3
4
5
6
7
8
postgres=# \d test
Table "public.test"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+------------------------------
id | integer | | not null | generated always as identity
value | text | | not null |
Indexes:
"test_value_key" UNIQUE CONSTRAINT, btree (value)

技巧0070 (\cd)

\cd元命令改变当前的工作目录。始自PG7.2

1
2
3
postgres=# \cd /tmp
postgres=# \! pwd
/private/tmp

技巧0071 (\d)

不带pattern的元命令\d会显示所有能见到的表、视图、物化视图、序列和外部表。

1
2
3
4
5
6
7
8
postgres=# \d
List of relations
Schema | Name | Type | Owner
--------+-------------+----------+----------
public | animal | table | laetitia
public | test | table | laetitia
public | test_id_seq | sequence | laetitia
(3 rows)

始自PG7.0, 9.0和9.3 得以更新。

技巧0072 (\d, \dS)

默认情况下,\d不会显示系统对象。你可以使用\dS或者\d带上pattern来包括系统对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
postgres=# \d
List of relations
Schema | Name | Type | Owner
--------+-------------+----------+----------
public | animal | table | laetitia
public | test | table | laetitia
public | test_id_seq | sequence | laetitia
(3 rows)

postgres=# \dS
List of relations
Schema | Name | Type | Owner
------------+---------------------------------+----------+----------
pg_catalog | pg_aggregate | table | postgres
pg_catalog | pg_am | table | postgres
pg_catalog | pg_amop | table | postgres
pg_catalog | pg_amproc | table | postgres
[...]
pg_catalog | pg_views | view | postgres
public | animal | table | laetitia
public | test | table | laetitia
public | test_id_seq | sequence | laetitia
(136 rows)

postgres=# \d pg_aggregate
Table "pg_catalog.pg_aggregate"
Column | Type | Collation | Nullable | Default
------------------+----------+-----------+----------+---------
aggfnoid | regproc | | not null |
aggkind | "char" | | not null |
aggnumdirectargs | smallint | | not null |
aggtransfn | regproc | | not null |
aggfinalfn | regproc | | not null |
aggcombinefn | regproc | | not null |
aggserialfn | regproc | | not null |
aggdeserialfn | regproc | | not null |
aggmtransfn | regproc | | not null |
aggminvtransfn | regproc | | not null |
aggmfinalfn | regproc | | not null |
aggfinalextra | boolean | | not null |
aggmfinalextra | boolean | | not null |
aggfinalmodify | "char" | | not null |
aggmfinalmodify | "char" | | not null |
aggsortop | oid | | not null |
aggtranstype | oid | | not null |
aggtransspace | integer | | not null |
aggmtranstype | oid | | not null |
aggmtransspace | integer | | not null |
agginitval | text | C | |
aggminitval | text | C | |
Indexes:
"pg_aggregate_fnoid_index" PRIMARY KEY, btree (aggfnoid)

始自 PG8.4

技巧0073(\d pattern)

带+号的\d 并带上pattern,会在前边\d pattern显示的结果的基础上,会显示各类信息的comment,像视图的定义、表的OID(如果出现的话),非默认的replica的identity设置。

1
2
3
4
5
6
7
8
9
postgres# \d+ test
Table "public.test"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
--------+---------+-----------+----------+------------------------------+----------+-------------+--------------+----------------
id | integer | | not null | generated always as identity | plain | | |
value | text | | not null | | extended | pglz | | column comment
Indexes:
"test_value_key" UNIQUE CONSTRAINT, btree (value)
Access method: heap

始自PG8.0

技巧0074(\dn)

\dn显示所有的schema列表。如果加上S,则同时会列出系统的schema。\dn Pattern会列出符合pattern的schema。+号则会显示访问权限和描述信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
postgres=# \dn
List of schemas
Name | Owner
--------+----------
public | postgres
(1 row)

postgres=# \dnS
List of schemas
Name | Owner
--------------------+----------
information_schema | postgres
pg_catalog | postgres
pg_toast | postgres
public | postgres
(4 rows)

postgres=# \dn+
List of schemas
Name | Owner | Access privileges | Description
--------+----------+----------------------+------------------------
public | postgres | postgres=UC/postgres+| standard public schema
| | =UC/postgres |
(1 row)

始自7.4, 8.0加入+, 9.0开始支持S。

技巧0075 (\db)

\db会列出所有表空间。\db pattern列出符合模式的表空间。+显示访问权限、选项、大小和描述信息。始自PG8.0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
postgres=# \db
List of tablespaces
Name | Owner | Location
------------+----------+-------------
myts | postgres | /pgccc/myts
pg_default | postgres |
pg_global | postgres |
(3 rows)

postgres=# \db+
List of tablespaces
Name | Owner | Location | Access privileges | Options | Size | Description
------------+----------+-------------+-------------------+---------+---------+-------------
myts | postgres | /pgccc/myts | | | 0 bytes |
pg_default | postgres | | | | 2683 MB |
pg_global | postgres | | | | 576 kB |
(3 rows)

始自PG8.0

技巧076 (\dD)

\dD会列出所有的domain,\dD pattern会列出所有符合pattern的domain。+会附带显示相关访问权限和描述信息。S会显示所有的系统domain。目前PostgreSQL并没有提供系统domain。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
postgres=# create domain public.ABC as int;
CREATE DOMAIN

postgres=# \dDS
List of domains
Schema | Name | Type | Collation | Nullable | Default | Check
--------+------+---------+-----------+----------+---------+-------
public | abc | integer | | | |
(1 row)

postgres=# \dD
List of domains
Schema | Name | Type | Collation | Nullable | Default | Check
--------+------+---------+-----------+----------+---------+-------
public | abc | integer | | | |
(1 row)

postgres=# \dD+
List of domains
Schema | Name | Type | Collation | Nullable | Default | Check | Access privileges | Description
--------+------+---------+-----------+----------+---------+-------+-------------------+-------------
public | abc | integer | | | | | |
(1 row)

技巧0077 (\ddp)

\ddp会显示所有默认权限设置。每一行一个role (带上schema, 如果有的话)。也可以带上pattern进行匹配。

始自PG7.3, 8.4加上了S, 9.2加上了+。

1
2
3
4
5
6
7
8
postgres=# alter default privileges for role test revoke all on tables from test;
ALTER DEFAULT PRIVILEGES
laetitia=# \ddp
Default access privileges
Owner | Schema | Type | Access privileges
-------+--------+-------+-------------------
test | | table |
(1 row)

技巧0078(\dE)

\dE列出所有外部表。\dE pattern,使用pattern进行匹配。+会展示存储、大小及描述信息。S会列出系统外部表。目前postgres并不带有任何系统外部表。始自PG9.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \dE
List of relations
Schema | Name | Type | Owner
--------+------+---------------+----------
public | logs | foreign table | postgres
(1 row)

postgres=# \dE+
List of relations
Schema | Name | Type | Owner | Persistence | Size | Description
--------+------+---------------+----------+-------------+---------+-------------
public | logs | foreign table | postgres | permanent | 0 bytes |
(1 row)

postgres=# \dES
List of relations
Schema | Name | Type | Owner
--------+------+---------------+----------
public | logs | foreign table | postgres
(1 row)

技巧0079 (\di)

\di列出所有的能见的索引。\di pattern带上模式匹配。+会显示存储、访问方法、大小和描述信息。S会显示系统索引。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
postgres=# \di
List of relations
Schema | Name | Type | Owner | Table
--------+----------------+-------+----------+-------
public | test_value_key | index | postgres | test
(1 row)

postgres=# \di+
List of relations
Schema | Name | Type | Owner | Table | Persistence | Access Method | Size | Description
--------+----------------+-------+----------+-------+-------------+---------------+-------+-------------
public | test_value_key | index | postgres | test | permanent | btree | 16 kB |
(1 row)

postgres=# \diS
List of relations
Schema | Name | Type | Owner | Table
------------+-----------------------------------------------+-------+----------+-------------------------
pg_catalog | pg_aggregate_fnoid_index | index | postgres | pg_aggregate
pg_catalog | pg_am_name_index | index | postgres | pg_am
pg_catalog | pg_am_oid_index | index | postgres | pg_ami
[...]
pg_catalog | pg_user_mapping_user_server_index | index | postgres | pg_user_mapping
public | test_value_key | index | postgres | test
(118 rows)

始自PG7.1, 7.2中加入了S, 8.4加入了+。

技巧0080 (\dm)

\dm会列出用户创建的可见的物化视图。\dm pattern,提供模式匹配。类似的会有+和S。目前postgres没有系统物化视图。始自PG9.3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \dm
List of relations
Schema | Name | Type | Owner
--------+------+-------------------+----------
public | mymv | materialized view | postgres
(1 row)

postgres=# \dm+
List of relations
Schema | Name | Type | Owner | Persistence | Access Method | Size | Description
--------+------+-------------------+----------+-------------+---------------+-------+-------------
public | mymv | materialized view | postgres | permanent | heap | 16 kB |
(1 row)

postgres=# \dmS
List of relations
Schema | Name | Type | Owner
--------+------+-------------------+----------
public | mymv | materialized view | postgres
(1 row)

技巧0081 (\ds)

列出所有用户创建的可见的序列,类似的有\ds pattern。S和+。始自PG7.1。7.2添加了S, 8.4添加了+。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
postgres=# \ds
List of relations
Schema | Name | Type | Owner
--------+-----------------------+----------+----------
public | mytest_id_seq | sequence | test
public | partition_test_id_seq | sequence | postgres
public | test_id_seq | sequence | postgres
(3 rows)

(3 rows)

postgres=# \ds+
Schema | Name | Type | Owner | Persistence | Size | Description
--------+-----------------------+----------+----------+-------------+------------+-------------
public | mytest_id_seq | sequence | test | permanent | 8192 bytes |
public | partition_test_id_seq | sequence | postgres | permanent | 8192 bytes |
public | test_id_seq | sequence | postgres | permanent | 8192 bytes |
List of relations
postgres=# \dsS
List of relations
Schema | Name | Type | Owner
--------+-----------------------+----------+----------
public | mytest_id_seq | sequence | test
public | partition_test_id_seq | sequence | postgres
public | test_id_seq | sequence | postgres
(3 rows)

技巧0082 (\dt)

\dt会列出所有的用户创建的可见的表。\dt pattern,加上了模式匹配。还有S和 +。+会显示存储、大小和描述信息。S会显示系统表。

始自PG7.1, 7.2中加入了S,8.4添加了+的支持。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
postgres=# \dt
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------------------+----------
public | animal | table | postgres
public | first_partition | table | postgres
public | mytest | table | test
public | partition_test | partitioned table | postgres
public | test | table | postgres
(5 rows)

postgres=# \dt+
List of relations
Schema | Name | Type | Owner | Persistence | Access Method | Size | Description
--------+-----------------+-------------------+----------+-------------+---------------+------------+---------------
public | animal | table | postgres | permanent | heap | 16 kB |
public | first_partition | table | postgres | permanent | heap | 8192 bytes |
public | mytest | table | test | permanent | heap | 0 bytes |
public | partition_test | partitioned table | postgres | permanent | | 0 bytes |
public | test | table | postgres | permanent | heap | 16 kB | table comment
(5 rows)

postgres=# \dtS
List of relations
Schema | Name | Type | Owner
------------+-------------------------+-------------------+----------
pg_catalog | pg_aggregate | table | postgres
pg_catalog | pg_am | table | postgres
[...]
public | partition_test | partitioned table | postgres
public | test | table | postgres
(67 rows)

技巧0083 (\dv)

\dv会列出用户创建的所有可见的视图。\dv pattern加入了模式匹配。还有符号S和+的支持。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
postgres=# \dv
List of relations
Schema | Name | Type | Owner
--------+--------+------+----------
public | myview | view | postgres
(1 row)

postgres=# \dv+
List of relations
Schema | Name | Type | Owner | Persistence | Size | Description
--------+--------+------+----------+-------------+---------+-------------
public | myview | view | postgres | permanent | 0 bytes |
(1 row)

postgres=# \dvS
List of relations
Schema | Name | Type | Owner
------------+---------------------------------+------+----------
pg_catalog | pg_available_extension_versions | view | postgres
pg_catalog | pg_available_extensions | view | postgres
[...]
pg_catalog | pg_views | view | postgres
public | myview | view | postgres
(72 rows)

技巧0084 (\des)

\des列出所有的外部服务器Foreign Server。\des pattern加入了模式支持。+会显示客外出的访问权限、类型、版本号、FDW选项以及描述信息。始自PG8.4

1
2
3
4
5
6
7
8
9
10
11
12
13
postgres=# \des
List of foreign servers
Name | Owner | Foreign-data wrapper
-------+----------+----------------------
pglog | postgres | file_fdw
(1 row)

postgres=# \des+
List of foreign servers
Name | Owner | Foreign-data wrapper | Access privileges | Type | Version | FDW options | Description
-------+----------+----------------------+-------------------+------+---------+-------------+-------------
pglog | postgres | file_fdw | | | | |
(1 row)

技巧0085 (\det)

\det列出所有的外部表(Foreign Table)。\det pattern加入了模式支持。+符号会显示FDW选项和描述信息。始自PG8.4

1
2
3
4
5
6
7
8
9
10
11
12
13
postgres=# \det
List of foreign tables
Schema | Table | Server
--------+-------+--------
public | logs | pglog
(1 row)

postgres=# \det+
List of foreign tables
Schema | Table | Server | FDW options | Description
--------+-------+--------+-----------------------------------------------+-------------
public | logs | pglog | (filename 'postgresql-Sun.csv', format 'csv') |
(1 row)

技巧0086 (\df)

\df显示 所有的用户创建的函数。\df pattern提供了模式匹配。+符号会显示可变性、并行安全性、属主、安全、访问权限、语言、源码以及描述。S符号会显示系统函数。

始自PG7.1,8.0支持+,8.4开始支持S。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
postgres=# \df
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------------------+------------------+---------------------+------
public | file_fdw_handler | fdw_handler | | func
public | file_fdw_validator | void | text[], oid | func
(2 rows)

postgres=# \df+
List of functions
Schema | Name | Result data type | Argument data types | Type | Volatility | Parallel | Owner | Security | Access privileges | Language | Source code | Description
--------+--------------------+------------------+---------------------+------+------------+----------+----------+----------+-------------------+----------+--------------------+-------------
public | file_fdw_handler | fdw_handler | | func | volatile | unsafe | postgres | invoker | | c | file_fdw_handler |
public | file_fdw_validator | void | text[], oid | func | volatile | unsafe | postgres | invoker | | c | file_fdw_validator |
(2 rows)

postgres=# \dfS xpath*
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+--------------+------------------+---------------------+------
pg_catalog | xpath | xml[] | text, xml | func
pg_catalog | xpath | xml[] | text, xml, text[] | func
pg_catalog | xpath_exists | boolean | text, xml | func
pg_catalog | xpath_exists | boolean | text, xml, text[] | func
(4 rows)

技巧0087 (\dfa)

\df后边跟一个a,表示所有的聚集函数,始自PG8.4

1
2
3
4
5
6
7
8
9
10
11
postgres=# \dfa variance 
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+----------+------------------+---------------------+------
pg_catalog | variance | numeric | bigint | agg
pg_catalog | variance | double precision | double precision | agg
pg_catalog | variance | numeric | integer | agg
pg_catalog | variance | numeric | numeric | agg
pg_catalog | variance | double precision | real | agg
pg_catalog | variance | numeric | smallint | agg
(6 rows)

技巧0088 (\dfn)

\dfn,表示所有的”normal”函数。始自PG8.4

1
2
3
4
5
6
7
postgres=# \dfn
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------------------+------------------+---------------------+------
public | file_fdw_handler | fdw_handler | | func
public | file_fdw_validator | void | text[], oid | func
(2 rows)

技巧0089 (\dfp)

在\df后边加上p, 表示只列出所有的procedure。始自PG11

1
2
3
4
5
6
postgres=# \dfp
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------------+------------------+---------------------+------
public | inset_data | | a text | proc
(1 row)

技巧0090(\dp)

\dft,表示所有的触发器函数。始自PG8.4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
postgres=# \dftS
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+------------------------------------+------------------+---------------------+------
pg_catalog | RI_FKey_cascade_del | trigger | | func
pg_catalog | RI_FKey_cascade_upd | trigger | | func
pg_catalog | RI_FKey_check_ins | trigger | | func
pg_catalog | RI_FKey_check_upd | trigger | | func
pg_catalog | RI_FKey_noaction_del | trigger | | func
pg_catalog | RI_FKey_noaction_upd | trigger | | func
pg_catalog | RI_FKey_restrict_del | trigger | | func
pg_catalog | RI_FKey_restrict_upd | trigger | | func
pg_catalog | RI_FKey_setdefault_del | trigger | | func
pg_catalog | RI_FKey_setdefault_upd | trigger | | func
pg_catalog | RI_FKey_setnull_del | trigger | | func
pg_catalog | RI_FKey_setnull_upd | trigger | | func
pg_catalog | suppress_redundant_updates_trigger | trigger | | func
pg_catalog | trigger_in | trigger | cstring | func
pg_catalog | tsvector_update_trigger | trigger | | func
pg_catalog | tsvector_update_trigger_column | trigger | | func
pg_catalog | unique_key_recheck | trigger | | func
(17 rows)

技巧0091 (\dfw)

\dfw列出所有的窗口函数,始自PG8.4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \dfwS
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+--------------+------------------+---------------------------------------+--------
pg_catalog | cume_dist | double precision | | window
pg_catalog | dense_rank | bigint | | window
pg_catalog | first_value | anyelement | anyelement | window
pg_catalog | lag | anycompatible | anycompatible, integer, anycompatible | window
pg_catalog | lag | anyelement | anyelement | window
pg_catalog | lag | anyelement | anyelement, integer | window
pg_catalog | last_value | anyelement | anyelement | window
pg_catalog | lead | anycompatible | anycompatible, integer, anycompatible | window
pg_catalog | lead | anyelement | anyelement | window
pg_catalog | lead | anyelement | anyelement, integer | window
pg_catalog | nth_value | anyelement | anyelement, integer | window
pg_catalog | ntile | integer | integer | window
pg_catalog | percent_rank | double precision | | window
pg_catalog | rank | bigint | | window
pg_catalog | row_number | bigint | | window
(15 rows)

技巧0092 (\d+)

\d+元命令,可以后续用 \comment SQL 命令来补充。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
postgres=# \d+ test
Table "public.test"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
--------+---------+-----------+----------+------------------------------+----------+-------------+--------------+----------------
id | integer | | not null | generated always as identity | plain | | |
value | text | | not null | | extended | pglz | | column comment
Indexes:
"test_value_key" UNIQUE CONSTRAINT, btree (value)
Access method: heap

postgres=# comment on column test.id IS 'My awesome comment';
COMMENT
postgres=# \d+ test
Table "public.test"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
--------+---------+-----------+----------+------------------------------+----------+-------------+--------------+--------------------
id | integer | | not null | generated always as identity | plain | | | My awesome comment
value | text | | not null | | extended | pglz | | column comment
Indexes:
"test_value_key" UNIQUE CONSTRAINT, btree (value)
Access method: heap

技巧0093 (\dg)

列出所有的用户创建的role。\dg pattern,S, +也都支持。始自PG8.0, 8.4开始支持+, 9.6开始支持S。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
postgres=# \dg
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {}

postgres=# \dg+
List of roles
Role name | Attributes | Member of | Description
-----------+------------------------------------------------------------+-----------+-------------
postgres | Superuser | {} |
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} |
test | | {} |

postgres=# \dgS
List of roles
Role name | Attributes | Member of
---------------------------+------------------------------------------------------------+--------------------------------------------------------------
postgres | Superuser | {}
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_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_server_files | Cannot login | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {}

技巧0094 (\dl)

\dl 列出所有的large object。始自PG7.1

1
2
3
4
5
postgres=# \dl
Large objects
ID | Owner | Description
----+-------+-------------
(0 rows)

技巧0095 (\dL)

\dL列出所有的用户创建的可见的过程语言。\df pattern支持模式匹配。+会显示它是否是内部语言、调用句柄、校验器,内联句柄、访问权限和描述信息。S会显示系统语言。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
postgres=# \dl
Large objects
ID | Owner | Description
----+-------+-------------
(0 rows)

postgres=# \dL
List of languages
Name | Owner | Trusted | Description
---------+----------+---------+------------------------------
plpgsql | postgres | t | PL/pgSQL procedural language
(1 row)

postgres=# \dL+
List of languages
Name | Owner | Trusted | Internal language | Call handler | Validator | Inline handler | Access privileges | Description
---------+----------+---------+-------------------+------------------------+------------------------+----------------------------------+-------------------+------------------------------
plpgsql | postgres | t | f | plpgsql_call_handler() | plpgsql_validator(oid) | plpgsql_inline_handler(internal) | | PL/pgSQL procedural language
(1 row)

postgres=# \dLS
List of languages
Name | Owner | Trusted | Description
----------+----------+---------+--------------------------------
c | postgres | f | dynamically-loaded C functions
internal | postgres | f | built-in functions
plpgsql | postgres | t | PL/pgSQL procedural language
sql | postgres | t | SQL-language functions
(4 rows)

技巧0096 (\dp)

\dp会列出所有的表、视图和序列它们对应的访问权限。\dp pattern支持模式匹配。始自7.1。关于那些访问权限,可以参考:

Table 5.2. Summary of Access Privileges

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
postges=# \dp
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+-----------------------+-------------------+---------------------------+-------------------+----------
public | animal | table | | |
public | first_partition | table | | |
public | logs | foreign table | | |
public | mymv | materialized view | | |
public | mytest | table | | |
public | mytest_id_seq | sequence | | |
public | myview | view | | |
public | partition_test | partitioned table | | |
public | partition_test_id_seq | sequence | | |
public | test | table | laetitia=arwdDxt/laetitia | |
public | test_id_seq | sequence | | |
(11 rows)

技巧0097 (\dP)

\dP列出所有的分区表及其索引。也支持\dP pattern和\dp+。始自PG12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=# \dP
List of partitioned relations
Schema | Name | Owner | Type | Table
--------+-----------------------+----------+-------------------+----------------
public | partition_test | laetitia | partitioned table |
public | partition_test_id_idx | laetitia | partitioned index | partition_test
(2 rows)

postgres=# \dP+
List of partitioned relations
Schema | Name | Owner | Type | Table | Total size | Description
--------+-----------------------+----------+-------------------+----------------+------------+-------------
public | partition_test | laetitia | partitioned table | | 8192 bytes |
public | partition_test_id_idx | laetitia | partitioned index | partition_test | 8192 bytes |
(2 rows)

技巧0098 (\dPi)

\dPi 列出分区表的索引,始自PG12

1
2
3
4
5
6
postgres=# \dPi
List of partitioned indexes
Schema | Name | Owner | Table
--------+-----------------------+----------+----------------
public | partition_test_id_idx | postgres | partition_test
(1 row)

技巧0099 (\dPt)

\dPt只列出分区表, 始自PG12

1
2
3
4
5
6
7
8
9
10
11
12
13
postgres=# \dPt
List of partitioned tables
Schema | Name | Owner
--------+----------------+----------
public | partition_test | postgres
(1 row)

postgres=# \dPt+
List of partitioned tables
Schema | Name | Owner | Total size | Description
--------+----------------+----------+------------+-------------
public | partition_test | postgres | 8192 bytes |
(1 row)

技巧0100 (\dPn)

\dPn显示非root分区的表和索引. \dPn+也支持。始自PG12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=# \dPn
List of partitioned relations
Schema | Name | Owner | Type | Parent name | Table
--------+-----------------------+----------+-------------------+-------------+----------------
public | partition_test | postgres | partitioned table | |
public | partition_test_id_idx | postgres | partitioned index | | partition_test
(2 rows)

postgres=# \dPn+
List of partitioned relations
Schema | Name | Owner | Type | Parent name | Table | Leaf partition size | Total size | Description
--------+-----------------------+----------+-------------------+-------------+----------------+---------------------+------------+-------------
public | partition_test | postgres | partitioned table | | | 8192 bytes | 8192 bytes |
public | partition_test_id_idx | postgres | partitioned index | | partition_test | 8192 bytes | 8192 bytes |
(2 rows)

技巧0101 (\copy)

\copy … to …,会让你从客户端机器拷贝数据。始自PG7.1

1
2
3
4
5
postgres=# \copy (select * from test) to mydata.dmp
COPY 2
postgres=# \! cat mydata.dmp
1 test
5 blabla

技巧0102 (\copy)

\copy元命令允许你将某些东西拷贝进表里头, 始自 PG7.1,包括 :命令的结果,程序或者标准输入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=# \copy test(value) from stdin
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> value1
>> value2
>> \.
COPY 2
postgres=# select * from test;
id | value
----+--------
1 | test
5 | blabla
6 | value1
7 | value2
(4 rows)

技巧0103 (\copy)

\copy与copy这个SQL命令不同,\copy元命令是运行在客户端上,不需要superuser权限,而copy则需要superuser权限或者具备下述权限之一才能执行:pg_read_server_files, pg_write_server_files, or pg_execute_server_program。始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
postgres=# \c postgres test
You are now connected to database "postgres" as user "test".
postgres=> \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+--------
postgres | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {}

postgres=> \copy (select * from test) to mydata.dmp
COPY 4
postgres=> \! cat mydata.dmp
1 test
5 blabla
6 value1
7 value2

技巧0104 (\copy)

\copy没有copy高效,因为所有数据必须经过client/server的网络连接。对于数据量很大的数据,copy显得更为高效。

技巧0105 (\copy)

(copy, \copy) stdin输入 的默认的分隔符是tab制表符。始自PG7.1

1
2
3
4
5
6
7
8
9
10
postgres=> create table data(d1 integer, d2 date);
CREATE TABLE
postgres=> \copy data from stdin
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself, or an EOF signal.
>> 1 '2021-04-12'
>> 2 '2021-04-13'
>> \.
ERROR: invalid input syntax for type integer: "2 '2021-04-13'"
CONTEXT: COPY data, line 2, column d1: "2 '2021-04-13'"

技巧0106 (\crosstabview)

\crosstabview这个元命令会从当前的查询buffer里创建一个crosstabview(交叉表视图)。默认情况下第一列会成为列头,第二列会成为水平的头, 第三列会填充整个表。始自PG9.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=> select * from music ;
artist | album | year
-----------------------+-------------------+------
Foo Fighters | Concrete and Gold | 2017
Red Hot Chili Peppers | The Getaway | 2016
Green Day | ¡Uno! | 2012
(3 rows)

postgres=> \crosstabview
artist | Concrete and Gold | The Getaway | ¡Uno!
-----------------------+-------------------+-------------+-------
Foo Fighters | 2017 | |
Red Hot Chili Peppers | | 2016 |
Green Day | | | 2012
(3 rows)

技巧0107 (\crosstabview)

你可以传列名给\crosstabview,以显示列的头和行的头.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=> select * from music ;
artist | album | year
-----------------------+-------------------+------
Foo Fighters | Concrete and Gold | 2017
Red Hot Chili Peppers | The Getaway | 2016
Green Day | ¡Uno! | 2012
(3 rows)

postgres=> \crosstabview artist year
artist | 2017 | 2016 | 2012
-----------------------+-------------------+-------------+-------
Foo Fighters | Concrete and Gold | |
Red Hot Chili Peppers | | The Getaway |
Green Day | | | ¡Uno!
(3 rows)

技巧0108 (\crosstabview)

可以用列的序号来指定行头和列头.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
postgres=> select * from music ;
artist | album | year
-----------------------+-------------------+------
Foo Fighters | Concrete and Gold | 2017
Red Hot Chili Peppers | The Getaway | 2016
Green Day | ¡Uno! | 2012
(3 rows)

postgres=> postgres=> \crosstabview 1 3
artist | 2017 | 2016 | 2012
-----------------------+-------------------+-------------+-------
Foo Fighters | Concrete and Gold | |
Red Hot Chili Peppers | | The Getaway |
Green Day | | | ¡Uno!
(3 rows)

技巧0109 (\drds)

\drds 显示指定的role一级的或者database一级的设置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
postgres=# \drds
List of settings
Role | Database | Settings
----------+----------+--------------------
postgres | | work_mem=250MB
| postgres | search_path=public+
| | work_mem=500MB
(2 rows)

postgres=# \drds * postgres
List of settings
Role | Database | Settings
------+----------+--------------------
| postgres | search_path=public+
| | work_mem=500MB
(1 row)

postgres=# \drds postgres
List of settings
Role | Database | Settings
----------+----------+----------------
postgres | | work_mem=250MB
(1 row)

技巧0110 (\dT)

列举数据类型列表。S符号允许列举系统数据类型。\dT pattern支持模式匹配。+则显示内部名、大小、元素及属主以及访问权限。始自PG7.1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \dT
List of data types
Schema | Name | Description
--------+---------------+-------------
public | one_word_only |
(1 row)

postgres=# \dTS line
List of data types
Schema | Name | Description
------------+------+----------------
pg_catalog | line | geometric line
(1 row)

postgres=# \dT+
List of data types
Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
--------+---------------+---------------+------+----------+----------+-------------------+-------------
public | one_word_only | one_word_only | var | | postgres | |
(1 row)

技巧0111 (\dT+)

列举数据类型列表。S符号允许列举系统数据类型。\dT pattern支持模式匹配。+则显示内部名、大小、元素及属主以及访问权限。始自PG7.1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \dT
List of data types
Schema | Name | Description
--------+---------------+-------------
public | one_word_only |
(1 row)

postgres=# \dTS line
List of data types
Schema | Name | Description
------------+------+----------------
pg_catalog | line | geometric line
(1 row)

postgres=# \dT+
List of data types
Schema | Name | Internal name | Size | Elements | Owner | Access privileges | Description
--------+---------------+---------------+------+----------+----------+-------------------+-------------
public | one_word_only | one_word_only | var | | postgres | |
(1 row)

技巧0112 (\du)

显示用户列表,自PG8.1起,用户和role就是一回事了。

S显示系统用户,du pattern支持匹配。+则显示每个role的描述信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {}

postgres=# \duS
List of roles
Role name | Attributes | Member of
---------------------------+------------------------------------------------------------+--------------------------------------------------------------
postgres | Superuser | {}
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 | {}
test | | {}

postgres=# \du+
List of roles
Role name | Attributes | Member of | Description
-----------+------------------------------------------------------------+-----------+-------------
postgres | Superuser | {} |
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} |
test | | {} |

始自PG7.2, 8.4支持+, 9.6支持S。

技巧0113 (\dg, \du)

自PG8.1起,group, user含义相同,不再区分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
postgres=# \dg
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-------------
grouptest | Cannot login | {}
postgres | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {grouptest}

postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-------------
grouptest | Cannot login | {}
postgres | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
test | | {grouptest}

技巧0114 (\dx)

\dx列出所有的 扩展 (extensions),它也支持\dx pattern ,而+是会同时显示所有属于目标扩展的对象。始自PG9.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
postgres=# \dx
List of installed extensions
Name | Version | Schema | Description
---------+---------+------------+------------------------------
plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language
(1 row)

postgres=# \dx+
Objects in extension "plpgsql"
Object description
-------------------------------------------
function plpgsql_call_handler()
function plpgsql_inline_handler(internal)
function plpgsql_validator(oid)
language plpgsql
(4 rows)

技巧0115 (\e)

\e或\edit, 将会把当前的查询缓冲,在默认编辑器里打开(或者使用PSQL_EDITOR、EDITOR、VISUAL设定的编辑器)

如果没有上述变量指定,则默认使用vi编辑器,在windows下则使用notepad.exe。

始自PG7.1

技巧0116(\e)

在psql上,我们可以用\e filename, 文件会被编辑器打开。保存关闭以后,它会被保存到查询缓冲里头。如果没有保存就退出,则缓冲被清空。

如果查询以;结束,则会立即执行。文件可以包含多个语句,psql会把它当作是单行命令,后续的所有东西都被当作是参数,即算换行也是如此。

始自PG7.1, 在PG14以前,即使没有保存,也会送到缓冲。

技巧0117 (\e)

\e filename linenumber直接定位文件的某一行。如果行号大于整个缓冲里头查询的数,则定位到最后一行。文件末尾有分号,则直接执行。始自9.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
postgres=# \e query.sql 3
?column?
----------
1
(1 row)

?column?
----------
2
(1 row)

?column?
----------
3
(1 row)

?column?
----------
4
(1 row)
postgres=# \! cat query.sql
select 1;
select 2;
select 3;
select 4;

技巧0118 (\echo)

显示 文本,或者变量的值到标准输出。可以使用-n作为第一个参数,去掉行末的换行符。始自PG7.1。

1
2
3
4
5
6
postgres=# \echo test
test
postgres=# \echo `date`
Fri Jul 30 10:13:41 CEST 2021
postgres=# \echo -n `date`
Fri Jul 30 10:13:47 CEST 2021postgres=#

技巧0119 (\qecho)

尽管\echo会把结果送到标准输出,你也可以用\qecho, 将内容写到文件(由\o指定)。始自PG7.1

1
2
3
4
5
6
7
postgres=# \o /tmp/output.out
postgres=# \echo `date`
Fri Jul 30 10:23:58 CEST 2021
postgres=# \! cat /tmp/output.out
postgres=# \qecho `date`
postgres=# \! cat /tmp/output.out
Fri Jul 30 10:24:25 CEST 2021

技巧0120 (\ef function)

\ef function将会打开相应函数的定义。如果有多个函数同名,你就需要把函数的签名也一块提供,这样PSQL才会知道要修改哪个函数。

1
2
3
4
5
6
7
8
9
10
11
12
postgres=# \df add_em
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+--------+------------------+----------------------------------------+------
public | add_em | double precision | x double precision, y double precision | func
public | add_em | integer | x integer, y integer | func
(2 rows)

postgres=# \ef add_em
ERROR: more than one function named "add_em"
postgres=# \ef add_em(integer, integer)
No changes

始自PG8.4, PG11开始支持过程。

技巧0121 (\ef function linenumber)

\ef function linenumber支持编辑函数中指定的行号

始自PG8.4, PG11开始支持过程。

技巧0122 (\ef)

\ef 不指定的时候,就会用缺省的模板,create function template。始自PG9.1, PG11开始支持过程。

技巧0123 (\ev)

\ev view会默认打开: create or replace view ,包含指定view的SQL代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
postgres=# \dv connection_settings
List of relations
Schema | Name | Type | Owner
--------+---------------------+------+----------
public | connection_settings | view | postgres
(1 row)

postgres=# \ev connection_settings
postgres=# CREATE OR REPLACE VIEW public.connection_settings AS
SELECT pg_settings.name,
pg_settings.setting,
pg_settings.unit
FROM pg_settings
WHERE pg_settings.name ~ 'connection'::text

始自PG9.6

技巧0124 (\ev)

如果没有view指定,\ev会使用默认的create view模板进行编辑。

技巧0125 (\ev view linenumber)

原理同上。

技巧0126 (\g)

\g元命令用于执行查询缓冲的最后一个查询。始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
postgres=# select * from test;
id | value
----+-------
1 | bla
2 | bla
3 | bla
4 | bla
5 | bla
6 | bla
(6 rows)

postgres=# \g
id | value
----+-------
1 | bla
2 | bla
3 | bla
4 | bla
5 | bla
6 | bla
(6 rows)

技巧0127 (\g)

可以用\g代替结束的; 表示相同的结果。始自PG7.1

1
2
3
4
5
6
7
8
9
10
postgres=# select * from test\g
id | value
----+-------
1 | bla
2 | bla
3 | bla
4 | bla
5 | bla
6 | bla
(6 rows)

技巧0128 (\g)

\g filename, 用于执行一次查询,将把结果存到文件里。如果不是绝对路径,则会存到当前目录里头。始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# select * from test;
id | col2
----+------
1 | test
2 | wang
3 | tttt
(3 rows)

postgres=# \g test.out
postgres=# \! cat test.out
id | col2
----+------
1 | test
2 | wang
3 | tttt
(3 rows)

postgres=# \! pwd
/var/lib/pgsql
postgres=#

技巧0129 (\g | command)

使用 \g | command可以把结果作为输入送到另一个 shell command里头。始自PG7.1

1
2
3
4
5
6
7
8
postgres=# select setting from pg_settings where name='data_directory';
setting
------------------------
/var/lib/pgsql/14/data
(1 row)

postgres=# \g | grep data
/var/lib/pgsql/14/data

技巧0130 (\g)

\g还可以带上一些格式化的选项。始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
postgres=# select * from test;
id | col2
----+------
1 | test
2 | wang
3 | tttt
(3 rows)

postgres=# \g (footer=off format=csv) test.out
postgres=# \! cat test.out
id,col2
1,test
2,wang
3,tttt
postgres=# \g (footer=off format=csv)
id,col2
1,test
2,wang
3,tttt

技巧0131 (\gdesc)

\gdesc 显示当前查询缓冲的描述信息(列名以及数据类型),并不执行查询。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
postgres=# select * from test;
id | col2
----+------
1 | test
2 | wang
3 | tttt
(3 rows)

postgres=# \gdesc
Column | Type
--------+-----------------------
id | integer
col2 | character varying(32)
(2 rows)

技巧0132 (\exec)

\exec元命令, 用于执行当前 查询缓冲的结果或者是最后一次查询(如果当前查询缓冲是空)。这个命令对于生成DDL非常有用,可以一次搞定。始自PG9.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
postgres=#  select 'drop table ' || table_name
postgres-# from information_schema.tables
postgres-# where table_schema = 'public'
postgres-# and table_name ~ 'test';
?column?
------------------
drop table test
drop table test2
(2 rows)

postgres=# \gexec
DROP TABLE
DROP TABLE
postgres=#

技巧0133 (\gset)

\gset 用于执行当前 查询缓冲的结果或者是最后一次查询(如果当前查询缓冲是空), 同时对结果的列名进行赋值。只有当查询的结果只有一行时,才能工作。始自PG9.3

1
2
3
4
5
6
7
8
9
10
postgres=# select id, 'ttt' as col2 from t limit 1;
id | col2
----+------
1 | ttt
(1 row)

postgres=# \gset
postgres=# \echo 'id: ' :id, 'value: ' :col2
id: 1, value: ttt
postgres=#

技巧0134 (\gset)

\gset prefix, 设定变量时指定前缀,其它同上。始自PG9.3

1
2
3
4
5
6
7
8
9
postgres=# select id, 'ttt' as col2 from t limit 1;
id | col2
----+------
1 | ttt
(1 row)

postgres=# \gset test_
postgres=# \echo 'id: ' :test_id, 'value: ' :test_col2
id: 1, value: ttt

技巧0135 (\gx)

\gx 用于执行当前 查询缓冲的结果或者是最后一次查询(如果当前查询缓冲是空),最后将行转列,扩展展示。始自PG10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
postgres=# select * from pg_settings where name = 'log_directory';
name | setting | unit | category | short_desc |
extra_desc | context | vartype | source | min_val | max_val | enumvals | boot_
val | reset_val | sourcefile | sourceline | pending_restart
---------------+---------+------+--------------------------------------+-----------------------------------------------+----------------
---------------------------------------------------------+---------+---------+--------------------+---------+---------+----------+------
----+-----------+----------------------------------------+------------+-----------------
log_directory | log | | Reporting and Logging / Where to Log | Sets the destination directory for log files. | Can be specifie
d as relative to the data directory or as absolute path. | sighup | string | configuration file | | | | log
| log | /var/lib/pgsql/14/data/postgresql.conf | 801 | f
(1 row)

postgres=# \gx
-[ RECORD 1 ]---+------------------------------------------------------------------------
name | log_directory
setting | log
unit |
category | Reporting and Logging / Where to Log
short_desc | Sets the destination directory for log files.
extra_desc | Can be specified as relative to the data directory or as absolute path.
context | sighup
vartype | string
source | configuration file
min_val |
max_val |
enumvals |
boot_val | log
reset_val | log
sourcefile | /var/lib/pgsql/14/data/postgresql.conf
sourceline | 801
pending_restart | f

技巧0136 (\gx filename)

\g, \gx可以把结果送往一个文件,始自PG10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
postgres=# \gx abc.out
postgres=# \! cat abc.out
-[ RECORD 1 ]---+------------------------------------------------------------------------
name | log_directory
setting | log
unit |
category | Reporting and Logging / Where to Log
short_desc | Sets the destination directory for log files.
extra_desc | Can be specified as relative to the data directory or as absolute path.
context | sighup
vartype | string
source | configuration file
min_val |
max_val |
enumvals |
boot_val | log
reset_val | log
sourcefile | /var/lib/pgsql/14/data/postgresql.conf
sourceline | 801
pending_restart | f

技巧0137 (\gx)

\gx也可以把结果送到另一个命令里头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
postgres=# select * from pg_settings where name = 'log_directory';
name | setting | unit | category | short_desc |
extra_desc | context | vartype | source | min_val | max_val | enumvals | boot_
val | reset_val | sourcefile | sourceline | pending_restart
---------------+---------+------+--------------------------------------+------------------------------------
log_directory | log | | Reporting and Logging / Where to Log | Sets the destination directory for log files. | Can be specifie
d as relative to the data directory or as absolute path. | sighup | string | configuration file | | | | log
| log | /var/lib/pgsql/14/data/postgresql.conf | 801 | f
(1 row)

postgres=# \gx | grep -i 'log'
name | log_directory
setting | log
category | Reporting and Logging / Where to Log
short_desc | Sets the destination directory for log files.
boot_val | log
reset_val | log

技巧0138 (\h)

\h给出任意SQL命令的语法. 始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
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

技巧0139 (\help)

\help 同上

技巧0140 (\h)

\h command显示具体的SQL命令的帮助信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
postgres=# \h vacuum
Command: VACUUM
Description: garbage-collect and optionally analyze a database
Syntax:
VACUUM [ ( option [, ...] ) ] [ table_and_columns [, ...] ]
VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ table_and_columns [, ...] ]

where option can be one of:

FULL [ boolean ]
FREEZE [ boolean ]
VERBOSE [ boolean ]
ANALYZE [ boolean ]
DISABLE_PAGE_SKIPPING [ boolean ]
SKIP_LOCKED [ boolean ]
INDEX_CLEANUP { AUTO | ON | OFF }
PROCESS_TOAST [ boolean ]
TRUNCATE [ boolean ]
PARALLEL integer

and table_and_columns is:

table_name [ ( column_name [, ...] ) ]

URL: https://www.postgresql.org/docs/14/sql-vacuum.html

技巧0141(\h)

\h command in multiple words ,一样会提供对应的命令的帮助。

1
2
3
4
5
6
7
postgres=# \h drop table
Command: DROP TABLE
Description: remove a table
Syntax:
DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]

URL: https://www.postgresql.org/docs/14/sql-droptable.html

技巧0142 (\H)

\H 或者 \html返回HTML格式的查询结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
postgres=# \H
Output format is html.
postgres=# select * from t limit 1;
<table border="1">
<tr>
<th align="center">id</th>
</tr>
<tr valign="top">
<td align="right">1</td>
</tr>
</table>
<p>(1 row)<br />
</p>

技巧0143 (\i)

\i filename或者\include filename,用于读取输入文件并执行。始自v7.1

1
2
3
4
5
6
7
postgres=# \! cat query.sql
select 1;
postgres=# \i query.sql
?column?
----------
1
(1 row)

技巧0144 (\l)

\l列出所有的数据库。似乎重复. (与0022)

技巧0145(\l)

\l pattern

1
2
3
4
5
6
7
8
postgres=# \l mydb
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
------+----------+----------+---------+-------+-----------------------
mydb | postgres | UTF8 | C | C | =Tc/postgres +
| | | | | postgres=CTc/postgres+
| | | | | mydb=CTc/postgres
(1 row)

技巧0146 (\l)

\l+ pattern, +多显示了存储,大小,表空间,描述信息. +支持,始自PG8.0

1
2
3
4
5
6
7
8
postgres=# \l+ mydb
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description
------+----------+----------+---------+-------+-----------------------+---------+------------+-------------
mydb | postgres | UTF8 | C | C | =Tc/postgres +| 8769 kB | pg_default |
| | | | | postgres=CTc/postgres+| | |
| | | | | mydb=CTc/postgres | | |
(1 row)

技巧0147 (\o)

\o指定输出文件,或者可以重置标准输出,始自PG7.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
postgres=# \o tmp.out
postgres=# select * from t limit 1;
postgres=# \! cat tmp.out
id
----
1
(1 row)

postgres=# \o
postgres=# select * from t limit 1;
id
----
1
(1 row)

技巧0148 (\o filename)

\o filename, 示例同上

技巧0149 (\o | command)

将\o的结果传给命令。

1
2
3
postgres=# \o | grep -i 'id'
postgres=# select * from t limit 1;
postgres=# id

技巧0150 (\p)

\p将当前的查询缓冲输出到标准输出,如果它为空,则把最后一次的缓冲输出。始自PG7.1

1
2
postgres=# \p
select * from t limit 1;

技巧0151 (\passwod username)

\password username,用于修改用户密码。始自PG8.2

1
2
3
postgres=# \password u1
Enter new password for user "u1":
Enter it again:

技巧0152 (\password)

\password不指定username时,则是修改当前user的密码,它能确保中间过程不会用到任何明文,也不会存到任何log里头,是一种安全的设置密码的行为。

[ END ]

参考:

  1. https://www.postgresql.org/docs/15/app-psql.html
  2. https://psql-tips.org/psql_tips_all.html
  3. https://zhuanlan.zhihu.com/p/65188460