Foreword:
Compared with MySQL or oracle, the postgresql database has an open source advantage, and the other is that the command line of the postgresql database is more abundant. Therefore, the management of the database is more convenient and fast, especially the short commands of postgresql can basically satisfy the daily database. Maintenance, management work out.
####Note: Short commands are usually used in the pg command line client, that is, psql -U user -p port -h database IP After logging in to the database, \c Such commands are called short commands and do not need to pass The commands for the client to log in to the database server, such as pg_controldata and pg_dump, are called long commands.
The following is a detailed introduction to the short commands of postgresql
one,
What are the query short commands?
\? is a help query command
test=# \?
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 [FILE] or ; execute query (and send results to file or |pipe)
\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 [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 [STRING] write string to standard output
\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 [STRING] write string to query output stream (see \o)
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
\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
\det[+] [PATTERN] list foreign tables
\des[+] [PATTERN] list foreign servers
\deu[+] [PATTERN] list user mappings
\dew[+] [PATTERN] list foreign-data wrappers
\df[anptw][S+] [PATRN] list [only agg/normal/procedures/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] [PATTERN] 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 [PATRN1 [PATRN2]] 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
\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 "test")
\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
It can be seen that there are many types of short commands by category, but some of them are very commonly used, which can effectively improve database operation and maintenance, management work,
Therefore, some short commands that are not commonly used or have a relatively low usage rate will be skipped or simply introduced in this article.
two,
Short commands for connection-side queries (very commonly used)
test=# \c
You are now connected to database "test" as user "postgres".
test=# \conninfo
You are connected to database "test" as user "postgres" via socket in "/tmp" at port "5432".
test=# \password postgres
Enter new password:
Enter it again:
The above command \c is to display abbreviated connection information. In this example, the super user postgres is used to connect to the database named test
\conninfo is the connection details. In this example, the super user postgres is used to connect to the database named test. The socket file is in the /tmp directory, and the connection port is 5432
\password postgres can be modified quickly and safely to modify the user password, but usually the super user postgres can modify other user passwords, this example is to modify the password of this user postgres
three,
All kinds of information query, mainly database, table, index, foreign key, primary key
Query the table name\d+ in the currently connected database or schema, and display the size of the table and the information it belongs to.
test=# \d
List of relations
Schema | Name | Type | Owner
--------+------+-------+----------
mytest | emp | table | postgres
(1 row)
test=# \d+
List of relations
Schema | Name | Type | Owner | Size | Description
--------+------+-------+----------+-------+-------------
mytest | emp | table | postgres | 16 kB |
(1 row)
Query tables and views only:
test-# \dp
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+----------------------+----------+-------------------+-------------------+----------
public | audit | table | | |
public | bonus | table | | |
public | company | table | | |
public | dept | table | | |
public | emp | table | | |
public | history_table | table | | |
public | history_table_id_seq | sequence | | |
public | salgrade | table | | |
public | tmp | table | | |
public | 計算機用語 | table | | |
(10 rows)
Which databases are queried, and the size of the database:
test-# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-------------------
pg1 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/pg1 +
| | | | | pg1=CTc/pg1
template1 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/pg1 +
| | | | | pg1=CTc/pg1
test | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
(5 rows)
test-# \l+
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges | Size | Tablespace | Description
-----------+----------+----------+-------------+-------------+-------------------+---------+------------+----------------------------
----------------
pg1 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 7953 kB | pg_default |
postgres | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 7993 kB | pg_default | default administrative conn
ection database
template0 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/pg1 +| 7809 kB | pg_default | unmodifiable empty database
| | | | | pg1=CTc/pg1 | | |
template1 | pg1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/pg1 +| 7809 kB | pg_default | default template for new da
tabases
| | | | | pg1=CTc/pg1 | | |
test | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 8849 kB | pg_default |
(5 rows)
Query the specific table structure, index, or view. According to the above command, continue to query the detailed information of the emp table and its primary key:
test=# \d emp
Table "mytest.emp"
Column | Type | Collation | Nullable | Default
----------+-----------------------+-----------+----------+---------
empno | numeric | | not null |
ename | character varying(10) | | |
job | character varying(9) | | |
mgr | numeric | | |
hiredate | date | | |
sal | numeric(7,2) | | |
comm | numeric(7,2) | | |
deptno | numeric(2,0) | | |
Indexes:
"pk_emp" PRIMARY KEY, btree (empno)
test=# \d pk_emp
Index "mytest.pk_emp"
Column | Type | Key? | Definition
--------+---------+------+------------
empno | numeric | yes | empno
primary key, btree, for table "mytest.emp"
Query the access methods supported by the database:
test=# \dA+
List of access methods
Name | Type | Handler | Description
--------+-------+----------------------+----------------------------------------
brin | Index | brinhandler | block range index (BRIN) access method
btree | Index | bthandler | b-tree index access method
gin | Index | ginhandler | GIN index access method
gist | Index | gisthandler | GiST index access method
hash | Index | hashhandler | hash index access method
heap | Table | heap_tableam_handler | heap table access method
spgist | Index | spghandler | SP-GiST index access method
(7 rows)
Query what are the existing table spaces, + display the size of the table space:
test=# \db
List of tablespaces
Name | Owner | Location
------------+-------+----------
pg_default | pg1 |
pg_global | pg1 |
(2 rows)
test=# \db+
List of tablespaces
Name | Owner | Location | Access privileges | Options | Size | Description
------------+-------+----------+-------------------+---------+--------+-------------
pg_default | pg1 | | | | 40 MB |
pg_global | pg1 | | | | 623 kB |
(2 rows)
Query functions, common functions, and functions related to triggers:
test=# \df
List of functions
Schema | Name | Result data type | Argument data types
| Type
--------+---------------------+-------------------+----------------------------------------------------------------------------------
------------------------------------+------
public | __tmp_create_user | void |
| func
public | auditlogfunc | trigger |
| func
public | copytable | integer | new_table_name character varying, old_table_name character varying, times integer
| func
public | emp | void | arr text[]
| func
public | emp_history_trigger | trigger |
| func
后面的略略略
test=# \dfn
List of functions
Schema | Name | Result data type | Argument data types
| Type
--------+-------------------+-------------------+------------------------------------------------------------------------------------
----------------------------------+------
public | __tmp_create_user | void |
| func
public | copytable | integer | new_table_name character varying, old_table_name character varying, times integer
| func
public | emp | void | arr text[]
| func
public | f_inittables1 | void | arr text[]
| func
public | ftest | character varying | fname character varying DEFAULT '水果'::character varying, cname character varying
DEFAULT '西瓜'::character varying | func
public | getsum | integer | talename character varying
| func
public | test | void | arr text[]
| func
public | totalrecords | integer |
| func
(8 rows)
test=# \dft
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+---------------------+------------------+---------------------+------
public | auditlogfunc | trigger | | func
public | emp_history_trigger | trigger | | func
public | record_history | trigger | | func
(3 rows)
Query all users and their details:
test-# \dg
List of roles
Role name | Attributes | Member of
--------------------+------------------------------------------------------------+-----------
pg1 | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
postgres | Superuser | {}
postgres_exporter | | {}
postgres_exporter1 | | {}
zsk | | {}
test-# \dg+
List of roles
Role name | Attributes | Member of | Description
--------------------+------------------------------------------------------------+-----------+-------------
pg1 | Superuser, Create role, Create DB, Replication, Bypass RLS | {} |
postgres | Superuser | {} |
postgres_exporter | | {} |
postgres_exporter1 | | {} |
zsk | | {} |
Query which schemas exist in the current database:
test-# \dn
List of schemas
Name | Owner
--------+----------
mytest | postgres
public | pg1
(2 rows)
test-# \dn+
List of schemas
Name | Owner | Access privileges | Description
--------+----------+-------------------+------------------------
mytest | postgres | |
public | pg1 | pg1=UC/pg1 +| standard public schema
| | =UC/pg1 |
(2 rows)
The definition of the query function (not very accurate, just a rough function definition):
test-# \sf copytable
CREATE OR REPLACE FUNCTION public.copytable(new_table_name character varying, old_table_name character varying, times integer)
RETURNS integer
LANGUAGE plpgsql
AS $function$
DECLARE
stmt1 varchar(1000);
stmt2 varchar(1000);
begin
for i in 1..times loop
raise notice '当前次数%',i;
stmt1 := format('create table "%1$s_%3$s" (like "%2$s" INCLUDING INDEXES INCLUDING DEFAULTS INCLUDING COMMENTS);',new_table_name,old_table_name,i);
stmt2 := format('insert into "%1$s_%3$s" select * from "%2$s" ;',new_table_name,old_table_name,i);
raise notice '%',stmt1;
raise notice '%',stmt2;
EXECUTE format('drop table if EXISTS "%1$s_%3$s";',new_table_name,old_table_name,i) ;
EXECUTE stmt1 ;
EXECUTE stmt2 ;
end loop;
return 110;
END; $function$
Definition of query view:
test=# create view emp_view as select empno,ename from emp;
CREATE VIEW
test=# \sv emp_view
CREATE OR REPLACE VIEW public.emp_view AS
SELECT emp.empno,
emp.ename
FROM emp
Four,
timing SQL statement execution timing
postgres=# \timing on
Timing is on.
postgres=# \timing off
Timing is off.
set quickly sets variables in the database, such as turning off autocommit, and prints all variables if no parameters are used:
postgres=# \set AUTOCOMMIT Off
Execute shell commands, sometimes it is not necessary to cut out the command line, which is more convenient
postgres=# \! ls ~/
1111.sh auto-sql.sh database-test.dump ewrwer.txt myglobals.sql test-backup test-database.sql test.tar.gz
12345.txt backup_log emp-bak1.sql logs SQL