postgresql |数据库 |postgresql数据库的短命令详细介绍

简介: postgresql |数据库 |postgresql数据库的短命令详细介绍

前言:

postgresql数据库相比较MySQL或者oracle,一个是开源优势,另一个就是postgresql数据库的命令行更为丰富,因此,数据库的管理工作更为方便,快捷,尤其是postgresql的短命令就可以基本满足日常的数据库维护,管理工作了。

####注:短命令通常是用在pg的命令行客户端的,也就是psql -U用户  -p 端口 -h 数据库IP 登陆数据库后 \c 这样的命令,我们称之为短命令,无需通过客户端登陆数据库服务端的,例如pg_controldata ,pg_dump 这些命令我们称之为长命令。

下面就postgresql的短命令做一个详细的介绍

一,

查询短命令有哪些?

\?是帮助查询命令

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

可以看到,短命令按类别分了很多种,但,其中有一些命令是非常常用的,可以有效提高数据库运维,管理工作的,

因此,一些不太常用的或者使用率比较低的短命令,本文将会略过或者只是简单的介绍。

二,

连接方面的查询的短命令(非常常用的)

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:

以上命令 \c 是显示简略连接信息,本例是使用超级用户postgres连接到了 名为test的数据库

\conninfo 是连接详细信息,本例是使用超级用户postgres连接到了 名为test的数据库,socket文件是/tmp目录下,连接端口是5432

\password postgres是快速d修改的,安全的修改用户密码,不过通常是postgres这个超级用户才可以修改其它用户密码,本例是修改本用户postgres的密码

三,

各类信息查询,主要是数据库,表,索引,外键,主键

查询当前连接的数据库或者schema内的表名称 \d+ 多显示表的大小以及所属这些信息。

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)

仅查询表和视图:

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)

查询有哪些数据库,以及数据库的大小:

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)

 

 

查询具体表结构,索引,或者视图,根据以上命令,在继续详细查询emp表和它的主键详细信息:

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"

查询该数据库支持的访问方法:

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)

查询现有的表空间有哪些,+显示表空间的大小:

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)

查询函数,普通函数,以及和触发器相关的函数:

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)

查询所有用户和用户的详细信息:

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                |                                                            | {}        | 

查询当前数据库下有哪些schema:

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)

查询函数的定义(不是很准确,只是个大概的函数定义内容):

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$

查询视图的定义:

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

四,

timing SQL语句执行计时

postgres=# \timing on
Timing is on.
postgres=# \timing off
Timing is off.

set 快速设置数据库内的变量,例如关闭自动提交,如果没有使用参数,就打印所有变量:

postgres=# \set AUTOCOMMIT Off

执行shell命令,某些时候不需要切出命令行,比较方便

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 
相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍如何基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
864 152
|
4月前
|
关系型数据库 MySQL 分布式数据库
阿里云PolarDB云原生数据库收费价格:MySQL和PostgreSQL详细介绍
阿里云PolarDB兼容MySQL、PostgreSQL及Oracle语法,支持集中式与分布式架构。标准版2核4G年费1116元起,企业版最高性能达4核16G,支持HTAP与多级高可用,广泛应用于金融、政务、互联网等领域,TCO成本降低50%。
|
4月前
|
关系型数据库 分布式数据库 数据库
阿里云数据库收费价格:MySQL、PostgreSQL、SQL Server和MariaDB引擎费用整理
阿里云数据库提供多种类型,包括关系型与NoSQL,主流如PolarDB、RDS MySQL/PostgreSQL、Redis等。价格低至21元/月起,支持按需付费与优惠套餐,适用于各类应用场景。
|
7月前
|
SQL 关系型数据库 MySQL
Go语言数据库编程:使用 `database/sql` 与 MySQL/PostgreSQL
Go语言通过`database/sql`标准库提供统一数据库操作接口,支持MySQL、PostgreSQL等多种数据库。本文介绍了驱动安装、连接数据库、基本增删改查操作、预处理语句、事务处理及错误管理等内容,涵盖实际开发中常用的技巧与注意事项,适合快速掌握Go语言数据库编程基础。
536 62
|
4月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎,提供高性价比、稳定安全的云数据库服务,适用于多种行业与业务场景。
|
5月前
|
存储 关系型数据库 数据库
【赵渝强老师】PostgreSQL数据库的WAL日志与数据写入的过程
PostgreSQL中的WAL(预写日志)是保证数据完整性的关键技术。在数据修改前,系统会先将日志写入WAL,确保宕机时可通过日志恢复数据。它减少了磁盘I/O,提升了性能,并支持手动切换日志文件。WAL文件默认存储在pg_wal目录下,采用16进制命名规则。此外,PostgreSQL提供pg_waldump工具解析日志内容。
462 0
|
7月前
|
存储 关系型数据库 分布式数据库
【赵渝强老师】基于PostgreSQL的分布式数据库:Citus
Citus 是基于 PostgreSQL 的开源分布式数据库,采用 shared nothing 架构,具备良好的扩展性。它以插件形式集成,部署简单,适用于处理大规模数据和高并发场景。本文介绍了 Citus 的基础概念、安装配置步骤及其在单机环境下的集群搭建方法。
594 2
|
4月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
179 3
|
4月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
5月前
|
存储 运维 关系型数据库
从MySQL到云数据库,数据库迁移真的有必要吗?
本文探讨了企业在业务增长背景下,是否应从 MySQL 迁移至云数据库的决策问题。分析了 MySQL 的优势与瓶颈,对比了云数据库在存储计算分离、自动化运维、多负载支持等方面的优势,并提出判断迁移必要性的五个关键问题及实施路径,帮助企业理性决策并落地迁移方案。

推荐镜像

更多