PostgreSql psql usage

1. Introduction to psql

  psql is a command-line interactive client tool in PostgreSQL, similar to the command-line tool sqlplus in Oracle, which allows users to interactively type in SQL statements or commands. In addition, it also provides some shortcut commands and a variety of Shell-like features to realize writing scripts, which is convenient for the automation of large-scale tasks. Although the function of psql is similar to that of sqlplus, it is far easier to use than sqlplus. For example, you can use the up and down arrow keys to flip out the previous and next SQL commands, and you can click the Tab key to automatically complete the function.

2. Connect to the interactive interface

2.1 Grammar

psql [option...] [dbname [username]]

dbname username : The database name username (the order cannot be wrong) is as follows:

[postgres@localhost ~]$ psql postgres postgres
psql (13.6)
Type "help" for help.

postgres=#

--有时 psql 后不加参数也可连接,原因为不带参数时,数据库及用户名默认值均为当前系统用户名,结果同上
[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.

postgres=#

optionOptional options :

-h hostname or --host=hostname : connection address.
-U username or --username=username : connect user.
-d dbname or --dbname=dbname : connect to the database name.
-p port or --port=port : connection port number.
-W or --password : The interactive interface after the carriage return is forced to enter the password, not the parameter followed by the password. In the background script of the user, it is configured at the end of the script, which will invalidate all the password-free logins set before.
-w or --no-password : Never enter a password in the interactive interface after the carriage return. In the background script of the common user, it needs to be used with the password parameter, such as PGPASSWORD=postgres psql -w, configured at the end of the script, will make the previously set All password authentication logins are invalid.
-c command or --command=command : Connect to the interactive interface to execute the sql command and then exit, which is commonly used in scripts.
-f filename or --file=filename : Exit after connecting to the interactive interface to execute the sql file, often used to import sql into the database. Equivalent to \i in the following meta-commands.
-o filename or --output=filename : Put all query output into the file filename. The current query does not display content, and the query sql is not included in the filename file. Equivalent to \o in the following meta-commands.
-L filename or --log-file=filename: Write all query output to the file filename in addition to the normal output destination. The current query shows the content, and the filename file contains the query sql.
-E : When connected to the interactive interface to execute shortcut meta-commands, the corresponding sql statement will be displayed. Equivalent to \set ECHO_HIDDEN on in the meta-command below.
-V or --version : Output psql version.
psql --help : Display psql usage help, if you have needs other than the above, query the usage help.

2.2 Examples

--交互界面时输入密码(-W 为强制输入密码,即便配置了免密登录策略也强制输入)
psql -h 192.168.100.115 -U postgres -d postgres -p 5432
psql -h 192.168.100.115 -U postgres -d postgres -p 5432 -W

--交互界面时不输入密码
PGPASSWORD=postgres psql -h 192.168.100.115 -U postgres -d postgres -p 5432 -w

--可也通过设置如下环境变量后,再执行 psql 命令连入,效果同上
export PGHOST=192.168.100.115
export PGUSER=postgres
export PGDATABASE=postgres
export PGPORT=5432
export PGPASSWORD=postgres
psql

--连入交互界面执行sql命令后退出
psql -c 'select version();'
等价于
psql
select version();
\q

[postgres@localhost ~]$ psql -c 'select version();'
                                                 version
---------------------------------------------------------------------------------------------------------
 PostgreSQL 13.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)

[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.

postgres=# select version();
                                                 version
---------------------------------------------------------------------------------------------------------
 PostgreSQL 13.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)

postgres=# \q
[postgres@localhost ~]$

--交互界面执行 sql 文件后退出
[postgres@localhost ~]$ cat select.sql
select * from emp;
[postgres@localhost ~]$ psql -f select.sql
 employee_id | first_name | last_name |  email   | phone_number | hire_date  |   job_id   |  salary  | commission_pct | manager_id | department_id
-------------+------------+-----------+----------+--------------+------------+------------+----------+----------------+------------+---------------
         100 | Steven     | King      | SKING    | 515.123.4567 | 2003-06-17 | AD_PRES    | 24000.00 |                |            |            90
         101 | Neena      | Kochhar   | NKOCHHAR | 515.123.4568 | 2005-09-21 | AD_VP      | 17000.00 |                |        100 |            90
         102 | Lex        | De Haan   | LDEHAAN  | 515.123.4569 | 2001-01-13 | AD_VP      | 17000.00 |                |        100 |            90
         103 | Alexander  | Hunold    | AHUNOLD  | 590.423.4567 | 2006-01-03 | IT_PROG    |  9000.00 |                |        102 |            60
         104 | Bruce      | Ernst     | BERNST   | 590.423.4568 | 2007-05-21 | IT_PROG    |  6000.00 |                |        103 |            60
         105 | David      | Austin    | DAUSTIN  | 590.423.4569 | 2005-06-25 | IT_PROG    |  4800.00 |                |        103 |            60
         106 | Valli      | Pataballa | VPATABAL | 590.423.4560 | 2006-02-05 | IT_PROG    |  4800.00 |                |        103 |            60
         107 | Diana      | Lorentz   | DLORENTZ | 590.423.5567 | 2007-02-07 | IT_PROG    |  4200.00 |                |        103 |            60
         108 | Nancy      | Greenberg | NGREENBE | 515.124.4569 | 2002-08-17 | FI_MGR     | 12008.00 |                |        101 |           100
         109 | Daniel     | Faviet    | DFAVIET  | 515.124.4169 | 2002-08-16 | FI_ACCOUNT |  9000.00 |                |        108 |           100
(10 rows)

[postgres@localhost ~]$

--查询结果输出到文件
[postgres@localhost ~]$ psql -c 'select * from emp' -o a.log
[postgres@localhost ~]$ cat a.log
 employee_id | first_name | last_name |  email   | phone_number | hire_date  |   job_id   |  salary  | commission_pct | manager_id | department_id
-------------+------------+-----------+----------+--------------+------------+------------+----------+----------------+------------+---------------
         100 | Steven     | King      | SKING    | 515.123.4567 | 2003-06-17 | AD_PRES    | 24000.00 |                |            |            90
         101 | Neena      | Kochhar   | NKOCHHAR | 515.123.4568 | 2005-09-21 | AD_VP      | 17000.00 |                |        100 |            90
         102 | Lex        | De Haan   | LDEHAAN  | 515.123.4569 | 2001-01-13 | AD_VP      | 17000.00 |                |        100 |            90
         103 | Alexander  | Hunold    | AHUNOLD  | 590.423.4567 | 2006-01-03 | IT_PROG    |  9000.00 |                |        102 |            60
         104 | Bruce      | Ernst     | BERNST   | 590.423.4568 | 2007-05-21 | IT_PROG    |  6000.00 |                |        103 |            60
         105 | David      | Austin    | DAUSTIN  | 590.423.4569 | 2005-06-25 | IT_PROG    |  4800.00 |                |        103 |            60
         106 | Valli      | Pataballa | VPATABAL | 590.423.4560 | 2006-02-05 | IT_PROG    |  4800.00 |                |        103 |            60
         107 | Diana      | Lorentz   | DLORENTZ | 590.423.5567 | 2007-02-07 | IT_PROG    |  4200.00 |                |        103 |            60
         108 | Nancy      | Greenberg | NGREENBE | 515.124.4569 | 2002-08-17 | FI_MGR     | 12008.00 |                |        101 |           100
         109 | Daniel     | Faviet    | DFAVIET  | 515.124.4169 | 2002-08-16 | FI_ACCOUNT |  9000.00 |                |        108 |           100
(10 rows)

[postgres@localhost ~]$

--查询结果输出并记录到文件
[postgres@localhost ~]$ psql -c 'select * from emp' -L b.log
 employee_id | first_name | last_name |  email   | phone_number | hire_date  |   job_id   |  salary  | commission_pct | manager_id | department_id
-------------+------------+-----------+----------+--------------+------------+------------+----------+----------------+------------+---------------
         100 | Steven     | King      | SKING    | 515.123.4567 | 2003-06-17 | AD_PRES    | 24000.00 |                |            |            90
         101 | Neena      | Kochhar   | NKOCHHAR | 515.123.4568 | 2005-09-21 | AD_VP      | 17000.00 |                |        100 |            90
         102 | Lex        | De Haan   | LDEHAAN  | 515.123.4569 | 2001-01-13 | AD_VP      | 17000.00 |                |        100 |            90
         103 | Alexander  | Hunold    | AHUNOLD  | 590.423.4567 | 2006-01-03 | IT_PROG    |  9000.00 |                |        102 |            60
         104 | Bruce      | Ernst     | BERNST   | 590.423.4568 | 2007-05-21 | IT_PROG    |  6000.00 |                |        103 |            60
         105 | David      | Austin    | DAUSTIN  | 590.423.4569 | 2005-06-25 | IT_PROG    |  4800.00 |                |        103 |            60
         106 | Valli      | Pataballa | VPATABAL | 590.423.4560 | 2006-02-05 | IT_PROG    |  4800.00 |                |        103 |            60
         107 | Diana      | Lorentz   | DLORENTZ | 590.423.5567 | 2007-02-07 | IT_PROG    |  4200.00 |                |        103 |            60
         108 | Nancy      | Greenberg | NGREENBE | 515.124.4569 | 2002-08-17 | FI_MGR     | 12008.00 |                |        101 |           100
         109 | Daniel     | Faviet    | DFAVIET  | 515.124.4169 | 2002-08-16 | FI_ACCOUNT |  9000.00 |                |        108 |           100
(10 rows)

[postgres@localhost ~]$ cat b.log
********* QUERY **********
select * from emp
**************************

 employee_id | first_name | last_name |  email   | phone_number | hire_date  |   job_id   |  salary  | commission_pct | manager_id | department_id
-------------+------------+-----------+----------+--------------+------------+------------+----------+----------------+------------+---------------
         100 | Steven     | King      | SKING    | 515.123.4567 | 2003-06-17 | AD_PRES    | 24000.00 |                |            |            90
         101 | Neena      | Kochhar   | NKOCHHAR | 515.123.4568 | 2005-09-21 | AD_VP      | 17000.00 |                |        100 |            90
         102 | Lex        | De Haan   | LDEHAAN  | 515.123.4569 | 2001-01-13 | AD_VP      | 17000.00 |                |        100 |            90
         103 | Alexander  | Hunold    | AHUNOLD  | 590.423.4567 | 2006-01-03 | IT_PROG    |  9000.00 |                |        102 |            60
         104 | Bruce      | Ernst     | BERNST   | 590.423.4568 | 2007-05-21 | IT_PROG    |  6000.00 |                |        103 |            60
         105 | David      | Austin    | DAUSTIN  | 590.423.4569 | 2005-06-25 | IT_PROG    |  4800.00 |                |        103 |            60
         106 | Valli      | Pataballa | VPATABAL | 590.423.4560 | 2006-02-05 | IT_PROG    |  4800.00 |                |        103 |            60
         107 | Diana      | Lorentz   | DLORENTZ | 590.423.5567 | 2007-02-07 | IT_PROG    |  4200.00 |                |        103 |            60
         108 | Nancy      | Greenberg | NGREENBE | 515.124.4569 | 2002-08-17 | FI_MGR     | 12008.00 |                |        101 |           100
         109 | Daniel     | Faviet    | DFAVIET  | 515.124.4169 | 2002-08-16 | FI_ACCOUNT |  9000.00 |                |        108 |           100
(10 rows)

[postgres@localhost ~]$


--显示元命令对应 sql
[postgres@localhost ~]$ psql -E
psql (13.6)
Type "help" for help.

postgres=# \l
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************

                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 test      | postgres | UTF8     | C           | C           |
 tpcc      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(6 rows)

3. Execute sql commands on the interactive interface

After connecting to the interactive interface, you can execute normal sql statements, the example is as follows (note that the psql interactive interface executes sql must end with a semicolon):

[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.
--建表
postgres=# create table test1(id int,name varchar);
CREATE TABLE
--插入数据
postgres=# insert into test1 values(1,'zhao'),(2,'qian'),(3,'sun');
INSERT 0 3
--查询
postgres=# select * from test1;
 id | name
----+------
  1 | zhao
  2 | qian
  3 | sun
(3 rows)

In the above example, the prompt postgres=# to enter the interactive interface explains :

postgres : The currently connected database.
= : The interactive interface is in the ready state. In this state, the command can be executed normally. The abnormal state is -, which is the state after the command is executed abnormally. After Ctrl+C exits the abnormal state and enters the ready state, the command can be executed normally.
# : The current connected user is a super-privileged user, and the prompt for a normal user is >.

--异常操作示例
postgres=# select * from test1
postgres-#
postgres-#
postgres-# ^C
postgres=# select * from test1;
 id | name
----+------
  1 | zhao
  2 | qian
  3 | sun
(3 rows)

--用普通用户切换至其他数据库后的提示符信息
postgres=# \c db1 syd
Password for user syd:
You are now connected to database "db1" as user "syd".
db1=>

4. Meta command

  The psql interactive interface provides a series of meta-commands for quick and easy query or setting. The meta-commands all start with a backslash \. Most query commands can be followed by a plus sign + to display query information in more detail.

4.1 Common query classes

  • \c : Display current connection information.
  • \c dbname : Switch the connected database.
  • \c username : Switch the connected user.
  • \c dbname name : Switch the connected user and database.
  • \l[+] : Display all database information.
  • \du[+] : Display all user information.
  • \dn[+] : Display all schema information in the current database.
  • \dx[+] : Display all extended information under the current database.
  • \dt[+] : Display all table information in the current schema in the current database.
  • \dv[+] : Display all view information in the current mode in the current database.
  • \di[+] : Display all index information in the current mode in the current database.
  • \ds[+] : Display all sequence information in the current mode in the current database.
  • \df[+] : Display all function information in the current mode in the current database.
  • \d jobname : Display the specific object structure, jobname can be the name of a specific table, view, index, or sequence.
  • \h sql : query sql syntax.
  • Wildcards are used : t*, the object starting with t; t??, the object starting with t, the length is three characters.
  • \set : View current psql environment variable settings.
  • \pset : View current psql output format settings.
  • \? : Display the usage introduction of all meta-commands.

Some examples :

--显示当前连接信息
postgres=# \c
You are now connected to database "postgres" as user "postgres".
--切换数据库
postgres=# \c db1
You are now connected to database "db1" as user "postgres".
db1=# \c postgres
You are now connected to database "postgres" as user "postgres".
--切换用户
postgres=# \c - syd
Password for user syd:
You are now connected to database "postgres" as user "syd".
postgres=> \c - postgres
You are now connected to database "postgres" as user "postgres".
--切换数据库和用户
postgres=# \c db1 syd
Password for user syd:
You are now connected to database "db1" as user "syd".
db1=> \c postgres postgres
You are now connected to database "postgres" as user "postgres".
--显示所有数据库信息
postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 test      | postgres | UTF8     | C           | C           |
 tpcc      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(6 rows)

postgres=# \l+
                                                                    List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   |  Size   | Tablespace |                Description
-----------+----------+----------+-------------+-------------+-----------------------+---------+------------+--------------------------------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 7885 kB | pg_default |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 29 MB   | pg_default | default administrative connection database
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7737 kB | pg_default | unmodifiable empty database
           |          |          |             |             | postgres=CTc/postgres |         |            |
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7737 kB | pg_default | default template for new databases
           |          |          |             |             | postgres=CTc/postgres |         |            |
 test      | postgres | UTF8     | C           | C           |                       | 945 MB  | pg_default |
 tpcc      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 8393 kB | pg_default |
(6 rows)
--显示 emp 表结构
postgres=# \d emp
                           Table "public.emp"
     Column     |         Type          | Collation | Nullable | Default
----------------+-----------------------+-----------+----------+---------
 employee_id    | integer               |           |          |
 first_name     | character varying(20) |           |          |
 last_name      | character varying(25) |           |          |
 email          | character varying(25) |           |          |
 phone_number   | character varying(20) |           |          |
 hire_date      | date                  |           |          |
 job_id         | character varying(10) |           |          |
 salary         | numeric(8,2)          |           |          |
 commission_pct | numeric(2,2)          |           |          |
 manager_id     | integer               |           |          |
 department_id  | integer               |           |          |

postgres=# \d+ emp
                                               Table "public.emp"
     Column     |         Type          | Collation | Nullable | Default | Storage  | Stats target | Description
----------------+-----------------------+-----------+----------+---------+----------+--------------+-------------
 employee_id    | integer               |           |          |         | plain    |              |
 first_name     | character varying(20) |           |          |         | extended |              |
 last_name      | character varying(25) |           |          |         | extended |              |
 email          | character varying(25) |           |          |         | extended |              |
 phone_number   | character varying(20) |           |          |         | extended |              |
 hire_date      | date                  |           |          |         | plain    |              |
 job_id         | character varying(10) |           |          |         | extended |              |
 salary         | numeric(8,2)          |           |          |         | main     |              |
 commission_pct | numeric(2,2)          |           |          |         | main     |              |
 manager_id     | integer               |           |          |         | plain    |              |
 department_id  | integer               |           |          |         | plain    |              |
Access method: heap
--通配符使用
postgres=# \dt t*
          List of relations
 Schema |   Name   | Type  |  Owner
--------+----------+-------+----------
 public | t_gist   | table | postgres
 public | t_spgist | table | postgres
 public | test     | table | postgres
 public | test0509 | table | postgres
 public | test1    | table | postgres
 public | ts       | table | postgres
 public | ttt      | table | postgres
(7 rows)

postgres=# \dt t??
        List of relations
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | ttt  | table | postgres
--查询建库语法
postgres=# \h create database
Command:     CREATE DATABASE
Description: create a new database
Syntax:
CREATE DATABASE name
    [ [ WITH ] [ OWNER [=] user_name ]
           [ TEMPLATE [=] template ]
           [ ENCODING [=] encoding ]
           [ LOCALE [=] locale ]
           [ LC_COLLATE [=] lc_collate ]
           [ LC_CTYPE [=] lc_ctype ]
           [ TABLESPACE [=] tablespace_name ]
           [ ALLOW_CONNECTIONS [=] allowconn ]
           [ CONNECTION LIMIT [=] connlimit ]
           [ IS_TEMPLATE [=] istemplate ] ]

URL: https://www.postgresql.org/docs/13/sql-createdatabase.html
--查询插入数据语法
postgres=# \h insert
Command:     INSERT
Description: create new rows in a table
Syntax:
[ WITH [ RECURSIVE ] with_query [, ...] ]
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
    [ OVERRIDING { SYSTEM | USER } VALUE ]
    { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
    [ ON CONFLICT [ conflict_target ] conflict_action ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

where conflict_target can be one of:

    ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
    ON CONSTRAINT constraint_name

and conflict_action is one of:

    DO NOTHING
    DO UPDATE SET { column_name = { expression | DEFAULT } |
                    ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
                    ( column_name [, ...] ) = ( sub-SELECT )
                  } [, ...]
              [ WHERE condition ]

URL: https://www.postgresql.org/docs/13/sql-insert.html

4.2 Common operation classes

  • \q : Quit the interactive interface.
  • \! command : Execute linux system commands.
  • \e filename : edit a file on linux.
  • \ev viewname : Edit view.
  • \ef functionname : Edit function.
  • \o : Output the execution result to an external file, the function is the same as the psql -o parameter above.
  • \i : Execute the external sql file stored on the operating system, the function is the same as the psql -f parameter above.

Some examples :

--退出交互界面
postgres=# \q
[postgres@localhost ~]$

--执行 linux 系统命令
postgres=# \! date
Sun Jun 25 10:11:05 CST 2023

[postgres@localhost ~]$ cat a.log
ssss
[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.

postgres=# \e /home/postgres/a.log
ssss
~
~

--编辑视图
postgres=# \d+ emp_v
                                       View "public.emp_v"
     Column     |         Type          | Collation | Nullable | Default | Storage  | Description
----------------+-----------------------+-----------+----------+---------+----------+-------------
 employee_id    | integer               |           |          |         | plain    |
 first_name     | character varying(20) |           |          |         | extended |
 last_name      | character varying(25) |           |          |         | extended |
 email          | character varying(25) |           |          |         | extended |
 phone_number   | character varying(20) |           |          |         | extended |
 hire_date      | date                  |           |          |         | plain    |
 job_id         | character varying(10) |           |          |         | extended |
 salary         | numeric(8,2)          |           |          |         | main     |
 commission_pct | numeric(2,2)          |           |          |         | main     |
 manager_id     | integer               |           |          |         | plain    |
 department_id  | integer               |           |          |         | plain    |
View definition:
 SELECT emp.employee_id,
    emp.first_name,
    emp.last_name,
    emp.email,
    emp.phone_number,
    emp.hire_date,
    emp.job_id,
    emp.salary,
    emp.commission_pct,
    emp.manager_id,
    emp.department_id
   FROM emp;

postgres=# \ev emp_v
CREATE OR REPLACE VIEW public.emp_v AS
 SELECT emp.employee_id,
    emp.first_name,
    emp.last_name,
    emp.email,
    emp.phone_number,
    emp.hire_date,
    emp.job_id,
    emp.salary,
    emp.commission_pct,
    emp.manager_id,
    emp.department_id
   FROM emp
~
~

4.3 Commonly used formatting and display classes

  • \x : Switch the query result display mode by row or column (default row display).
  • \set ECHO_HIDDEN on : Display the sql statement specifically executed by the meta-command, the function is the same as the psql -E parameter above.

Example :

--切换查询结果行/列展示模式
postgres=# select * from dept;
 department_id | department_name
---------------+-----------------
             1 | Adminstration
             2 | Marketing
            30 | Purchasing
(3 rows)

postgres=# \x
Expanded display is on.
postgres=# select * from dept;
-[ RECORD 1 ]---+--------------
department_id   | 1
department_name | Adminstration
-[ RECORD 2 ]---+--------------
department_id   | 2
department_name | Marketing
-[ RECORD 3 ]---+--------------
department_id   | 30
department_name | Purchasing

postgres=# \x
Expanded display is off.
postgres=# select * from dept;
 department_id | department_name
---------------+-----------------
             1 | Adminstration
             2 | Marketing
            30 | Purchasing
(3 rows)

--显示元命令具体执行 sql
postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 test      | postgres | UTF8     | C           | C           |
 tpcc      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(6 rows)

postgres=# \set ECHO_HIDDEN on
postgres=# \l
********* QUERY **********
SELECT d.datname as "Name",
       pg_catalog.pg_get_userbyid(d.datdba) as "Owner",
       pg_catalog.pg_encoding_to_char(d.encoding) as "Encoding",
       d.datcollate as "Collate",
       d.datctype as "Ctype",
       pg_catalog.array_to_string(d.datacl, E'\n') AS "Access privileges"
FROM pg_catalog.pg_database d
ORDER BY 1;
**************************

                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 test      | postgres | UTF8     | C           | C           |
 tpcc      | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(6 rows)

Five, the use of skills

5.1 Queries only show results

psql -c -At returns only the results, often used in scripts.

[postgres@localhost ~]$ psql -c  'select * from student;'
 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

[postgres@localhost ~]$ psql -c  'select * from student;' -At
3|王二|15
1|张三|14

5.2 Display SQL execution time

The \timing meta-command is used to turn display of SQL execution timing on or off.

postgres=# \timing
Timing is on.
postgres=# select * from student;
 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

Time: 1.010 ms
postgres=# \timing
Timing is off.
postgres=# select * from student;
 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

5.3 Repeat the execution of the current sql

The \watch [seconds] meta-command will repeat the SQL command of the current query buffer (that is, the last sql), and the default is two seconds until it terminates or fails.

postgres=# select * from student;
 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

postgres=# \watch
Tue 11 Jul 2023 05:51:53 PM CST (every 2s)

 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

Tue 11 Jul 2023 05:51:55 PM CST (every 2s)

 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

^Cpostgres=# \watch 0.05
Tue 11 Jul 2023 05:52:05 PM CST (every 0.05s)

 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

Tue 11 Jul 2023 05:52:05 PM CST (every 0.05s)

 student_no | student_name | age
------------+--------------+-----
          3 | 王二         |  15
          1 | 张三         |  14
(2 rows)

5.4 Modify psql default rules

~/.psqlrc file custom settings, when psql connects to the database, it will automatically execute the settings in this file, such as changing the default automatic submission of psql to manual submission.

--默认自动提交开启
[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.

postgres=# \set
AUTOCOMMIT = 'on'
……
……

--配置自动提交关闭
[postgres@localhost ~]$ cat ~/.psqlrc
\set AUTOCOMMIT off
[postgres@localhost ~]$ psql
psql (13.6)
Type "help" for help.

postgres=# \set
AUTOCOMMIT = 'off'
……
……

Guess you like

Origin blog.csdn.net/songyundong1993/article/details/131372854
Recommended