PostgreSQL 入门与实战指南|从基础概念到 CentOS 部署、运维、CRUD 完整教程

PostgreSQL

摘要:本文是一篇全面的 PostgreSQL 入门与实战指南。首先介绍了 PostgreSQL 的历史、特性、市场排名以及与 MySQL 的详细对比,帮助读者理解其定位。接着详细讲解了在 CentOS 系统上的安装步骤,包括二进制安装和源码编译安装两种方式,并提供了 pg_ctl 命令管理数据库的完整示例。管理部分涵盖了配置文件、数据库概念、psql 工具使用、连接管理以及常用操作(数据库/表/索引/表空间创建与管理、CRUD、系统信息查看等)。最后介绍了图形化管理工具 pgAdmin 的安装与配置。全文包含大量命令行示例和截图,适合数据库初学者和开发者系统学习 PostgreSQL。

1 PostgreSQL介绍和特性

官方首页:PostgreSQL: The world's most advanced open source database

官方软件下载页:PostgreSQL: Downloads

1.1 PostgreSQL介绍

PostgreSQL是当前功能最强大的开源的关系型数据库系统,支持跨平台的多种操作系统,基于C语言开 发。通常简称为PG或PGSQL。

PostgreSQL宣称是世界上最先进的开源数据库。PostgreSQL的狂热者认为它的性能缺Oracle不分上下, 而且没有高成本的负担。

PostgreSQL拥有看悠久的历史,可以追搠到1985年的加州大学伯克利分校的项目POSTGRES,是1977年 的由数据库科学家MichaelStonebraker领导的lngres项目的行生品,为了专注于数据库理论的研究,在 版本4.2时伯克利正式终止了POSTGRES项目。

1994年,来自中国香港的两名伯克利的研究生Andrew Yu和JollyChen向POSTGRES中增加了现在SQL语 言的解释器,将Postgres改名为Postgres95,并将其源代码发布到互联网上,成为一个开源的数据库管 理系统。

1996年,Postgres95名称已经不合时宜,被更改为PostgresQL,表示它支持查询语言标准,同时版本号 也重新从6.0开始。自从版本6.0之后,出现了很多后续发行版本。

PostgreSQL是100%社区驱动的开源项自,由全球范围内干人以上的社区责献者共同维护。PostgreSQL 提供了一个完整功能的瓶本,而不像MySQL那样提供多个不同的瓶本,如社区版、商业版及企业版。

PostgreSQL的开源协议采用自由的BSD,MTT类型,这种开源协议允许任何人在保留版权声明的情况下 使用,夏制,修改或者分享代码。

可靠性是PostgreSQL最优先关注的特性。普遍认为PostgreSQL坚如磐石并且设计精密,能够支持事务处 理和关键任务应用。PostgreSQL提供一流的文档服务,包括全面的免费在线手册,以及旧版本手册的存 档。社区的支持非常出色,并且有独立厂商提供商业支持。

数据一致性和完整性也是PostgeSQL的高度优先事项。PostgreSQL是完全符合ACID原则(原子性、一致 性、隔离性,持久性)的数据库:PostgreSQL对数据库访问提供强大的安全控制,不仅能够利用企业安 全工具,如:Kerberos和OpenSSL等,还可以根据自己的业务规则自定义核对方法,以确保数据的质 量。数据库 管理员最喜欢的功能是时间点恢复(point-in-timerecovery简称PITR)期能,它具有灵活性,高可用性特 征,能够打造快速故障的热备份服务器,以及快照和恢复到特定时间点等。但这还不是全部,该项目提 供了很多方法来管理PostgreSQL,使PostgreSQL具有高可用性、负载均衡和同步功能,因此可以利用这 些功能来满足特定需求

PostgreSQL开源许可

复制代码
https://www.postgresql.org/about/licence/

1.2数据库排名

复制代码
https://db-engines.com/en/ranking

1.3 PostgresQL与MySQL对比

一、核心定位与设计理念
MySQL
  • 主打易用、轻量、读写快、运维简单,互联网中小业务、建站、APP 后端主流

  • 架构偏简单高效,优先牺牲部分高级特性换取速度

  • 社区庞大,生态工具、云厂商支持全面(阿里云、腾讯云、AWS 等)

  • 主流存储引擎:InnoDB(事务)、MyISAM(无事务,已淘汰)

PostgreSQL(PG)
  • 标准企业级全功能关系型数据库,严格遵循 SQL 标准,学术出身,功能完整度极高

  • 设计优先数据完整性、复杂查询、扩展能力、高级 SQL 特性

  • 适合复杂业务、数据分析、GIS、金融、政企、多类型混合数据场景

  • 单存储引擎(内置统一存储层),无引擎切换成本

二、核心功能对比表
对比维度 MySQL(InnoDB) PostgreSQL
SQL标准 部分兼容,存在大量私有语法,很多标准特性缺失 高度兼容 SQL:2003/2016,几乎完整支持标准语法
事务/ACID 完整支持,MVCC 完整支持 MVCC,隔离级别更丰富
事务隔离级别 读未提交、读已提交、可重复读(默认)、串行化 多一级:可序列化快照隔离 (Snapshot),无幻读问题
数据类型 基础类型为主,扩展弱 极丰富:数组、JSONB、地理GIS、范围类型、自定义类型、UUID、IP、树形ltree
JSON 支持 JSON/JSON5,索引性能一般 JSONB(二进制json,支持GIN/GIST高效索引,原生JSON操作强)
窗口函数 8.0后支持,功能有限 完整全套窗口函数,支持复杂分析
CTE递归 8.0支持递归CTE 原生完善递归CTE,树形层级查询极强
存储过程/函数 语法简陋,仅支持SQL/简单逻辑 支持 PL/pgSQL、Python、Java、JS 等多语言存储过程
自定义扩展 扩展生态少 海量开源扩展:pg_stat_statements、pg_cron、pg_vector、pg_graphql、TimescaleDB时序库
全文检索 内置简易,能力弱,依赖ES 原生高性能全文检索,支持分词、权重、模糊匹配
地理空间/GIS 简单Point,弱,需第三方插件 内置完整PostGIS,专业GIS数据库标准,地图轨迹首选
并行查询 有限并行,仅简单查询 完善并行:聚合、JOIN、扫描、分区全部可并行
分区表 分区类型少,性能一般 范围 / 列表 / 哈希 / 复合分区,分区裁剪高效,支持分区触发器
约束性能 完整外键性能差,大量外键拖慢写入 外键、检查约束、排他约束强,性能损耗低
向量数据库 无原生向量,依赖第三方 原生向量类型vector,pg_vector扩展做AI向量检索
多版本并发MVCC 回滚日志undo,事务ID复用,长事务易膨胀 元组多版本,vacuum清理,长事务影响可控
三、性能差异
1. 简单 CRUD、高并发写入(互联网短事务)
  • MySQL 优势:轻量、内存开销更小,简单单表插入 / 更新 / 查询吞吐量更高

  • 适合:高并发短请求、商品订单简单表、小程序、CMS 网站

2. 复杂查询、多表 JOIN、聚合、报表、大数据量分析
  • PostgreSQL 碾压:优化器更智能,支持并行、哈希 JOIN、完善统计信息

  • 千万级多表关联、分组统计、子查询、递归树形数据 PG 速度远快 MySQL

3. 读写混合、大量复杂约束 / 外键

PG 性能衰减更小,InnoDB 外键多的时候写入会明显卡顿

4. 大数据批量导入

PG copy 批量加载性能远超 MySQL load data

四、并发与锁机制
  1. MySQL InnoDB

行锁基于索引,无索引会降级表锁

锁粒度粗,更新范围大极易触发表级意向锁冲突

默认可重复读隔离,存在幻读问题

  1. PostgreSQL

MVCC 无共享锁,读写完全不阻塞

支持行级、页级、表级多种锁,粒度精细

快照隔离彻底解决幻读,适合高并发读写混合场景

五、扩展性
MySQL
  • 横向扩展成熟:分库分表(Sharding-JDBC、MyCat)

  • 主从复制简单,读写分离方案普及

  • 垂直扩展上限低,复杂单库上亿数据容易瓶颈

PostgreSQL
  1. 垂直扩展能力极强

自定义数据类型、操作符、索引方法、聚合函数

插件化架构,不用改内核就能新增功能(时序、向量、图数据库)

  1. 复制:流复制、逻辑复制、多副本、级联复制

  2. 分库分表生态不如 MySQL 成熟,但 Citus 扩展可实现分布式 PG 集群

六、运维与成本
MySQL
  • 学习门槛低,DBA 人才多,排错资料遍地

  • 资源占用低,低配服务器就能跑

  • 备份、监控、迁移工具生态极其完善

  • 缺点:版本间语法差异大,升级易踩坑

PostgreSQL
  • 功能复杂,学习曲线陡峭,资深 DBA 相对少

  • 内存配置要求更高,大数据场景需要更大内存

  • 版本升级平滑,SQL 标准统一,升级改动小

  • 自带监控、日志、性能诊断工具完善

七、适用场景推荐
✅ 优先选 MySQL
  1. 中小型互联网业务,简单 CRUD、高并发短事务(电商订单、小程序、CMS、博客)

  2. 团队 MySQL 技术栈成熟,人手充足

  3. 需要快速分库分表水平扩容

  4. 硬件资源有限,低配服务器部署

  5. 仅存储结构化简单数据,无复杂查询、分析需求

✅ 优先选 PostgreSQL
  1. 复杂业务系统:ERP、金融、政务、制造,强数据一致性、多外键约束

  2. 报表、BI、数据分析、多表复杂 JOIN、批量统计

  3. 存储混合数据:JSON 业务配置、地理轨迹 GIS、数组、树形结构

  4. AI 向量检索、时序数据(搭配 TimescaleDB)、图查询

  5. 需要递归查询、树形组织(菜单、组织架构、层级审批)

  6. 对 SQL 标准、数据完整性要求极高,不接受数据库自动隐式类型转换等不规范行为

八、总结一句话
  • MySQL:轻量化、高吞吐简单业务首选,生态成熟易上手,适合互联网高并发短事务

  • PostgreSQL:全能企业级数据库,SQL 标准完整、复杂查询 / 多类型数据 / GIS / 向量能力拉满, 适合重业务、分析、混合数据场景

1.4各种数据库性能比较

性能对比简表
负载场景 最优 中等 短板选手
简单单表高并发读写 MySQL PG、SQLServer Oracle 单机
多表复杂 JOIN、报表 PostgreSQL Oracle MySQL
批量导入 / 大批量插入 PostgreSQL(COPY) MySQL SQL Server
海量分布式事务 OceanBase Oracle RAC MySQL 分库分表
JSON/JSONB 检索、数组索引 PostgreSQL MySQL SQL Server
GIS、树形递归查询 PostgreSQL Oracle MySQL

1.5 PostgreSQL各版本的特性矩阵

复制代码
https://www.postgresql.org/about/featurematrix/

2 PostgreSQL安装

安装方法分为两种:

  • 二进制安装包进行安装

各个Linux的发行版本中,很多都内置了PostgreSQL的二进制安装包,但内置的版本可能较旧。对 于二进制 包安装的方法是通过不同发行版本的Linux下的包 管理器进行的,如在RHEL系统相关版本下 用yum 命令,在Debian或Ubuntu下使用apt 命令

  • 源码编译安装

使用源码编译安装相对更灵活,用户可以有更多的选择,可以选择较新的版本、配置不同的编译选 项,编译 出用户需要的功能。

官方安装文档:

复制代码
https://www.postgresql.org/download/

2.1CentOS安装 PostgreSQL

如今,大多数常见操作系统都提供PostgreSQL二进制软件包。如果有可用的二进制软件包,对于该操作 系统的用户来说,这是安装PostgreSQL的推荐方式。只有开发PostgreSQL或其扩展的人员,才建议从源 码构建。

PostgreSQL支持各种操作系统,并提供相关二进制包包的安装方法

复制代码
https://www.postgresql.org/download/linux/redhat/
2.1.1 2进制安装
2.1.2 Centos Stream8利用官方源安装PostgreSQL-18
bash 复制代码
# 在线安装 PostgreSQL 官方 YUM 源配置包
dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# 禁用系统内置的postgresql模块
dnf -qy module disable postgresql

# 安装postgresql18
dnf install -y postgresql18-server

# 初始化数据库
/usr/pgsql-18/bin/postgresql-18-setup initdb

# 设置开机自启并启动服务
systemctl enable postgresql-18
systemctl start postgresql-18

# 验证方式1:root用户直接执行sql查看版本
[root@localhost ~]# sudo -u postgres psql -c "SELECT VERSION();"
                                         version
------------------------------------------------------------------------------------------
 PostgreSQL 18.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-28), 64-bit
(1 row)

# 验证方式2:切换postgres系统用户进入psql交互终端
[root@localhost ~]# su - postgres
[postgres@localhost ~]$ psql
psql (18.4)
Type "help" for help.

postgres=# help
You are using psql, the command‑line interface to PostgreSQL.
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
postgres=#

范例:Centos Stream8利用系统源安装PostgreSQL-10

bash 复制代码
# 使用yum安装系统自带postgresql‑server(RHEL8内置PostgreSQL10)
[root@localhost ~]# yum install postgresql-server

# 默认直接启动失败
[root@localhost ~]# systemctl start postgresql.service
Job for postgresql.service failed because the control process exited with error code.
See "systemctl status postgresql.service" and "journalctl -xe" for details.

# 查看系统日志,提示数据库目录未初始化
[root@localhost ~]# tail /var/log/messages
Jul 13 20:57:01 localhost systemd[1]: postgresql.service: Failed with result 'exit-code'.
Jul 13 20:57:01 localhost systemd[1]: Failed to start PostgreSQL database server.
Jul 13 20:57:15 localhost systemd[1]: Starting PostgreSQL database server...
Jul 13 20:57:15 localhost postgresql-check-db-dir[11068]: Directory "/var/lib/pgsql/data" is missing or empty.
Jul 13 20:57:15 localhost postgresql-check-db-dir[11068]: Use "/usr/bin/postgresql-setup --initdb"
Jul 13 20:57:15 localhost postgresql-check-db-dir[11068]: to initialize the database cluster.
Jul 13 20:57:15 localhost postgresql-check-db-dir[11068]: See /usr/share/doc/postgresql/README.rpm-dist for more information.
Jul 13 20:57:15 localhost systemd[1]: postgresql.service: Control process exited, code=exited status=1
Jul 13 20:57:15 localhost systemd[1]: postgresql.service: Failed with result 'exit-code'.
Jul 13 20:57:15 localhost systemd[1]: Failed to start PostgreSQL database server.

# 确认数据目录为空
[root@localhost ~]# ls /var/lib/pgsql/data/

# 执行数据库初始化
[root@localhost ~]# /usr/bin/postgresql-setup --initdb
* Initializing database in '/var/lib/pgsql/data'
* Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log

# 初始化完成,查看生成的数据文件
[root@localhost ~]# ls /var/lib/pgsql/data/
base  pg_commit_ts  pg_ident.conf  pg_notify     pg_snapshots  pg_subtrans  PG_VERSION  postgresql.auto.conf
global  pg_dynshmem  pg_logical     pg_replslot   pg_stat       pg_tblspc    pg_wal      postgresql.conf
log     pg_hba.conf  pg_multixact   pg_serial     pg_stat_tmp   pg_twophase  pg_xact

# 启动服务并设置开机自启
[root@localhost ~]# systemctl start postgresql.service
[root@localhost ~]# systemctl enable postgresql.service

# 验证数据库版本(警告:无法切换到/root目录,属于正常提示,不影响SQL执行)
[root@localhost ~]# sudo -u postgres psql -c "SELECT VERSION();"
could not change directory to "/root": Permission denied
                                         version
------------------------------------------------------------------------------------------
 PostgreSQL 10.23 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-20), 64-bit
(1 row)

2.2 pg_ctl 命令管理 PostgreSQL

pg_ctl是一个实用的命令行工具,有以下常见功能:

  • 初始化PostgreSQL数据库实例

  • 启动、终止或重启PostgresQL数据库服务。

  • 查看PostgreSQL数据库服务的状态

  • 让数据库实例重新读取配置文件。允许给一个指定的PostgreSQL进程发送信号

  • 控制standby服务器为可读写

  • 在Windows平台下允许为数据库实例注册或取消一个系统服务

pc_ctl命令格式

bash 复制代码
# 将PostgreSQL18 bin目录追加到全局环境变量
[root@localhost ~]# echo PATH=$PATH:/usr/pgsql-18/bin/ >> /etc/profile
[root@localhost ~]# source /etc/profile

# 切换postgres系统用户
[root@localhost ~]# su - postgres

# 查看pg_ctl帮助信息
[postgres@localhost ~]$ pg_ctl --help
pg_ctl is a utility to initialize, start, stop, or control a PostgreSQL server.

Usage:
  pg_ctl init[db]   [-D DATADIR] [-s] [-o OPTIONS]
  pg_ctl start      [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s] [-o OPTIONS] [-p PATH] [-c]
  pg_ctl stop       [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]
  pg_ctl restart    [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s] [-o OPTIONS] [-c]
  pg_ctl reload     [-D DATADIR] [-s]
  pg_ctl status     [-D DATADIR]
  pg_ctl promote    [-D DATADIR] [-W] [-t SECS] [-s]
  pg_ctl logrotate  [-D DATADIR] [-s]
  pg_ctl kill       SIGNALNAME PID

Common options:
  -D, --pgdata=DATADIR   location of the database storage area
  -s, --silent           only print errors, no informational messages
  -t, --timeout=SECS    seconds to wait when using -w option
  -V, --version          output version information, then exit
  -w, --wait             wait until operation completes (default)
  -W, --no-wait          do not wait until operation completes
  -?, --help             show this help, then exit

If the -D option is omitted, the environment variable PGDATA is used.

Options for start or restart:
  -c, --core-files       allow postgres to produce core files
  -l, --log=FILENAME     write (or append) server log to FILENAME
  -o, --options=OPTIONS  command line options to pass to postgres
                         (PostgreSQL server executable) or initdb
  -p PATH-TO-POSTGRES    normally not necessary

Options for stop or restart:
  -m, --mode=MODE        MODE can be "smart", "fast", or "immediate"

Shutdown modes are:
  smart       quit after all clients have disconnected
  fast        quit directly, with proper shutdown (default)
  immediate   quit without complete shutdown; will lead to recovery on restart

Allowed signal names for kill:
  ABRT HUP INT KILL QUIT TERM USR1 USR2

Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>
2.2.1初始化实例

初始化PostgreSQL数据库实例的命令如下:

bash 复制代码
# 先切换用户 
[root@localhost ~]# su - postgres

# 两种方式 
initdb [OPTION]... [DATADIR] 
pg_ctl init[db] [-D DATADIR] [-s] [-o OPTIONS]

#pg_ctl命令调用initdb命令创建了一个新的PostgresQL数据库实例,参数说明如下。 
-s #只打印错误和警告信息,不打印提示性信息。 
-D DATADIR#指定数据库实例的数据目录。如果没有指定DATADIR,使用环境变量PGDATA指定的路径 
-o options#为直接传递给initdb命令的参数

范列:创建新的数据库实例实例

bash 复制代码
# 使用pg_ctl init初始化一套全新PG18数据目录(多实例测试)
[postgres@localhost ~]$ pg_ctl init -D /var/lib/pgsql/18/data2
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are enabled.

creating directory /var/lib/pgsql/18/data2 ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default "max_connections" ... 100
selecting default "shared_buffers" ... 128MB
selecting default time zone ... Asia/Shanghai
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

initdb: warning: enabling "trust" authentication for local connections
initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

/usr/pgsql-18/bin/pg_ctl -D /var/lib/pgsql/18/data2 -l logfile start

# 查看PG18根目录,已生成data2实例目录
[postgres@localhost ~]$ ls /var/lib/pgsql/18/
backups  data  data2  initdb.log

# 查看data2实例下完整数据文件
[postgres@localhost ~]$ ls /var/lib/pgsql/18/data2
base          pg_dynshmem   pg_logical    pg_replslot   pg_stat       pg_tblspc     pg_wal          postgresql.conf
global        pg_hba.conf   pg_multixact  pg_serial     pg_stat_tmp   pg_twophase   pg_xact
pg_commit_ts  pg_ident.conf pg_notify     pg_snapshots  pg_subtrans   PG_VERSION    postgresql.auto.conf
2.2.2 服务管理
2.2.2.1查看服务状态

查询数据库实例状态的命令如下:

复制代码
pg_ctl status    [-D DATADIR]

范例:

bash 复制代码
# 查看默认实例(/var/lib/pgsql/18/data)运行状态
[postgres@localhost ~]$ pg_ctl status
pg_ctl: server is running (PID: 1253)
/usr/pgsql-18/bin/postgres "-D" "/var/lib/pgsql/18/data/"

# 指定data2数据目录查看第二个实例状态,未启动
[postgres@localhost ~]$ pg_ctl status -D /var/lib/pgsql/18/data2
pg_ctl: no server running
2.2.2.2启动服务

启动PostgreSQL服务的命令:

复制代码
pg_ctl start     [-D DATADIR] [-l FILENAME] [-W] [-t SECS] [-s]

#参数说明如下。 
start #启动数据库实例 
-w #等待启动完成 
-t #等待启动完成的等待秒数,默认为60秒 
-s #只打印错误和警告信息,不打印提示性信息 
-D datadir #指定数据库实例的数据目录 
-l #服务器日志输出附加在"fi1ename"文件上,如果该文件不存在则创建它 
-o options #声明要直接传递给postgres的选项,具体可见postgres命令的帮助 
-p path#指定postgres可执行文件的位置。默认情况下postgres可执行文件来自和pg_ctl相同的目录,不 必使用该选项。除非要进行一些不同寻常的操作,或者产生了postgres执行文件找不到的错误 
-c #提高服务器的软限制(ulimit-c),尝试允许数据库实例在有异常时产生一个coredump文件,以便于问 题定位和故障分析

范例:

bash 复制代码
# 尝试启动第二个PG实例data2,启动失败
[postgres@localhost ~]$ pg_ctl start -D /var/lib/pgsql/18/data2
waiting for server to start....2026-07-14 21:23:43.140 CST [2042] LOG:  redirecting log output to logging collector process
2026-07-14 21:23:43.140 CST [2042] HINT:  Future log output will appear in directory "log".
stopped waiting
pg_ctl: could not start server
Examine the log output.

# 查看日志,根因:5432端口已被第一个实例占用
[postgres@localhost ~]$ cat /var/lib/pgsql/18/data2/log/postgresql-Tue.log
2026-07-14 21:24:01.326 CST [2048] LOG:  could not bind IPv6 address "::1": Address already in use

2026-07-14 21:24:01.326 CST [2048] HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
2026-07-14 21:24:01.326 CST [2048] LOG:  could not bind IPv4 address "127.0.0.1": Address already in use
2026-07-14 21:24:01.326 CST [2048] HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
2026-07-14 21:24:01.326 CST [2048] WARNING:  could not create listen socket for "localhost"
2026-07-14 21:24:01.326 CST [2048] FATAL:  could not create any TCP/IP sockets
2026-07-14 21:24:01.326 CST [2048] LOG:  database system is shut down

# 修改data2实例配置文件,修改监听端口为5433
[postgres@localhost ~]$ vi /var/lib/pgsql/18/data2/postgresql.conf
port = 5433

# 修改端口后成功启动实例
[postgres@localhost ~]$ pg_ctl start -D /var/lib/pgsql/18/data2
waiting for server to start....2026-07-14 21:33:19.585 CST [2098] LOG:  redirecting log output to logging collector process
2026-07-14 21:33:19.585 CST [2098] HINT:  Future log output will appear in directory "log".
done
server started

# 校验data2实例运行状态
[postgres@localhost ~]$ pg_ctl status -D /var/lib/pgsql/18/data2
pg_ctl: server is running (PID: 1973)
/usr/pgsql-18/bin/postgres "-D" "/var/lib/pgsql/18/data2"
2.2.2.3 停止服务

停止PostgreSQL数据库命令如下:

复制代码
pg_ctl stop   [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s] 
# 参数说明如下。 
-W #不等待数据库停下来,命令就返回。 
-m #指定停止的模式。前面已叙述过停止的几种模式了。 
# 其它未说明的参数,其含义与启动数据库命令中的参数相同。

范例:

bash 复制代码
# 停止data2实例
[postgres@localhost ~]$ pg_ctl stop -D /var/lib/pgsql/18/data2
waiting for server to shut down.... done
server stopped

# 查看实例状态,已停止
[postgres@localhost ~]$ pg_ctl status -D /var/lib/pgsql/18/data2
pg_ctl: no server running
2.2.2.4重启服务

重启PostgreSQL数据库的命令如下:

复制代码
pg_ctl restart   [-D DATADIR] [-m SHUTDOWN-MODE] [-W] [-t SECS] [-s]

范例:

bash 复制代码
# 重启data2实例(实例已停止,无pid文件,直接执行start)
[postgres@localhost ~]$ pg_ctl restart -D /var/lib/pgsql/18/data2
pg_ctl: PID file "/var/lib/pgsql/18/data2/postmaster.pid" does not exist
Is server running? trying to start server anyway
waiting for server to start....2026-07-14 21:41:53.033 CST [2140] LOG:  redirecting log output to logging collector process
2026-07-14 21:41:53.033 CST [2140] HINT:  Future log output will appear in directory "log".
done
server started

# 查看实例状态,重启成功
[postgres@localhost ~]$ pg_ctl status -D /var/lib/pgsql/18/data2
pg_ctl: server is running (PID: 2140)
/usr/pgsql-18/bin/postgres "-D" "/var/lib/pgsql/18/data2"
2.2.2.5 加载配置

在配置文件中改变参数后,需要使用上面这条命令使参数生效

bash 复制代码
# 修改配置文件postgresql.conf后,让修改生效的方法有两种

# 方法一:在操作系统使用下面命令 
pg_ctl reload [-D DATADIR] [-s]

# 方法二:在 psql 中使用如下命令 
postgres=# select pg_reload_conf();

#注意:加载配置操作只针对一些配置的修改生效,有些配置需要重新启动服务才能生效

范例:

bash 复制代码
# 重载配置
[postgres@localhost ~]$ pg_ctl reload -D /var/lib/pgsql/18/data2
server signaled

# 注意:修改端口不支持reload,只能restart;修改listen_addresses支持reload
[postgres@localhost ~]$ vi /var/lib/pgsql/18/data2/postgresql.conf
listen_addresses = '*'

# 重载配置生效
[postgres@localhost ~]$ pg_ctl reload -D /var/lib/pgsql/18/data2
server signaled

# 重载后监听仍然仅本地回环
[postgres@localhost ~]$ ss -nlt | grep 5433
LISTEN 0      200          127.0.0.1:5433            0.0.0.0:*
LISTEN 0      200                [::1]:5433               [::]:*

# 重启实例使listen_address完整生效
[postgres@localhost ~]$ pg_ctl restart -D /var/lib/pgsql/18/data2
waiting for server to shut down.... done
server stopped
waiting for server to start....2026-07-14 21:50:32.529 CST [2189] LOG:  redirecting log output to logging collector process
2026-07-14 21:50:32.529 CST [2189] HINT:  Future log output will appear in directory "log".
done
server started

# 重启成功,监听0.0.0.0所有网卡
[postgres@localhost ~]$ ss -nlt | grep 5433
LISTEN 0      200            0.0.0.0:5433            0.0.0.0:*
LISTEN 0      200               [::]:5433               [::]:*

3 PostgreSQL管理

3.1配置文件介绍

PostgreSQL使用环境变量PGDATA指向的目录做为数据存放的目录。这个目录是在安装时指定的,所以 在安装时需要指定一个合适的目录作为数据目录的根目录,而且,每一个PG数据库实例都需要有这样的 一个目录。此数据目录的初始化是使用命令initdb来完成的。

初始化完成后,PGDATA数据目录下就会生成三个配置文件。

复制代码
postgresql.conf #数据库实例的主配置文件,基本上所有的配置参数都在此文件中。 
pg_hba.conf #认证配置文件,配置了允许哪些IP的主机访问数据库,认证的方法是什么等信息。 
pg_ident.conf #认证方式ident的用户映射文件。

3.2数据库相关概念

3.2.1数据库的结构组织

在一个PostgreSQL数据库系统中,数据的组织结构可以分为以下五层:

  • 实例:一个PostgreSQL对应一个安装的数据目录$PGDATA,即一个instance实例

  • 数据库:一个PostgreSQL数据库服务下可以管理多个数据库,当应用连接到一个数据库时,一般只 能访问这个数据库中的数据,而不能访问其他数据库中的内容

  • 默认情况下初始实例只有三个数据库:postgres、template0、template1

  • 模式:一个数据库可以创建多个不同的名称空间即Schema,用于分隔不同的业务数据

  • 表和索引:一个数据库可以有多个表和索引。在PostgreSQL中表的术语称为Relation,而在其他数 据库中通常叫Table

  • 行和列:每张表中有很多列和行数据。在PostgreSQL中行的术语一般为"Tuple",而在其他数据库中 则叫"Row"。

3.2.2 PostgreSQL中的术语

PostgreSQL有一些术语与其他数据库中不一样,了解了这些术语的意思,就能更好地看懂PostgreSQL中 的文档。

与其他数据库不同的术语如下。

  • Relation:表示表table或索引index,具体表示的是Table还是Index需要看具体情况

  • Tuple:表示表中的行,在其他数据库中使用Row来表示

  • Segment:每个表和索引都单独对应一个文件.即为segment,如果文件大小超过1GB,会创建多个相 同名称但后缀不同的文件

  • Page:表示在磁盘中的数据块。在文件中以块为单位存放数据,默认值为8KB,最大可以为32KB

  • Buffer:表示在内存中的数据块。

3.2.3模版数据库template0 和 template1

template1和template0是PostgreSQL的模板数据库。所谓模板数据库就是创建新database时, PostgreSQL会基于模板数据库制作一份副本,其中会包含所有的数据库设置和数据文件。

PostgreSQL安装好以后会默认附带两个模板数据库:默认模板库为template1和template1。

默认模板库为template1,也可以指定template0

比如:create database db1 template template0

不要对templateo模板数据库进行任何修改,因为这是原始的干净模板

如果其它模板数据库被搞坏了,基于这个数据库做一个副本就可以了。

如果希望定制自己的模板数据库,那么请基于template1进行修改,或者自己另外创建一个模板数据库再 修改。

template1和template0的区别主要有两点:

1、template1可以连接,template0不可以连接。

2、使用template1模板库建库时不可指定新的encoding和locale,而template0可以。

注意:template0和template1都不能被删除。

3.2.4模式 schema

模式schema是数据库中的一个概念,可以将其理解为一个命名空间。不同的模式下可以有相同名称的 表、函数等对象且互相不冲突。提出模式的概念是为了便于管理,只要有权限,每个模式(schema)的 对象可以互相调用。

在PostgreSQL中,一个数据库包含一个或多个模式,一个模式中又包含了表、函数及操作符等数据库对 象。

在PostgreSQL中,不能同时访问不同数据库中的对象,当要访问另一个数据库中的表或其他对象时,需 要重新连接到这个新的数据库,而模式没有此限制。一个用户在连接到一个数据库后,就可以同时访问 这个数据库中多个模式的对象。

通常情况下,创建和访问表的时候都不用指定模式,实际上这时访问的都是public模式。每当我们创建一 个新的数据库时,PostgreSQL都会自动创建一个名为public的模式。当登录到该数据库时,如果没有特 殊的指定,都是以该模式public操作各种数据对象的。

我们需要使用模式有以下几个主要原因:

  • 允许多个用户在使用同一个数据库时彼此互不干扰。

  • 把数据库对象放在不同的模式下,然后组织成逻辑组,让它们更便于管理。

  • 第三方的应用可以放在不同的模式中,这样就不会和其他对象的名字冲突了。

bash 复制代码
#创建模弐 
create schema schema_name;

#删除模式 
drop schema schema_name;

#查看模式 
\dn

要访问指定模式中的对象,需要先指定一个包含模式名及表名的名字,模式和表之间用一个"点"分开,

如下:

复制代码
schema_name.table_name

3.3psql工具介绍和基本用法

psql是PostgreSQL中的一个命令行交互式客户端工具,类似MySQL的mysql和Oracle中的命令行工具 sqIplus,它允许你交互地输入SQL或命令,然后把它们发出给PostgreSQL服务器,再显示SQL或命令的 结果。而且,输入的内容还可以来自于一个文件。此外,它还提供了一些命令和多种类似shell的特性来 实现书写脚本,从而实现对大量任务的自动化工作。

虽然也可以使用PostgreSQL中图形化的客户端工具(如pgadmin)来实现上述功能。但如果掌握了psql的 使用方法,将会体会到它的方便之处。因为psql是一个字符界面的工具,没有图形化工具使用上的一些 限制。psql与pgAdminl之间的关系类似于vi与某些图形化工具的关系。

psql的历史命令与补全的功能

  • 可以使用上下键把以前使用过的命令或SQL语句调出来

  • 连续按两个tab键表示把命令补全或给出提示输入

psql 命令格式

bash 复制代码
psql-h <hostname or ip> -p<端口> [数据库名称] -U [用户名称]

-h #指定要连接的数据库主机名或IP地址,默认localsocket登录(由配置项 unix_socket_directories指定)

-p #指定连接的数据库端口 #最后两个参数是数据库名和用户名

#这些连接参数也可以用环境变量指定,比如: 
export PGDATABASE=testdb 
export PGHOST=192.168.108.200 
export PGPORT=5432 
export PGUSER=postgres

#然后运行psql即可,其效果与运行psql -h 192.168.108.200 -p 5432 testdb postgres相同。

范例:psql本地登录PGSQL

bash 复制代码
[root@localhost ~]# su - postgres

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

postgres=#

范例:远程登录

bash 复制代码
#注意:默认PostgreSQL不支持远程登录,需要修改配置和授权才可以 
#如果不指定he11odb数据库,默认连接和用户名同名的数据库 
[postgres@localhost ~]$ psql -h 192.168.108.200 -p 5432 hellodb postgres

范例:psql命令中直接执行SQL

bash 复制代码
[postgres@localhost ~]$ psql -d postgres -c "select current_time"
    current_time 
--------------------
 17:08:25.507614+08 
(1 row)

范例:psql命令中执行文件中的SQL

bash 复制代码
#编辑SQL文件
[postgres@localhost ~]$ vim test.sql
select current_time;
\du

#进入psql交互终端
[postgres@localhost ~]$ psql
psql (18.4)
Type "help" for help.

# \i <文件名> 执行存储在外部文件中的sql语句或元命令
postgres=# \i test.sql
    current_time
--------------------
 17:12:25.837359+08
(1 row)

                                     List of roles
 Role name |                         Attributes
-----------+------------------------------------------------------------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS

3.4连接管理

3.4.1访问控制配置文件介绍

在PostgreSQL中,带有一个网络防火墙的功能的文件pg_hba.conf可以控制允许设置哪些IP的机器访问 数据库服务器。

HBA的意思是host-based authentication,也就是基于主机的认证,即实现PostgreSQL防火墙功能

initdb初始化数据目录时,会生成一个默认的pg_hba.conf文件。

pg_hba.conf文件的格式由很多记录组成,每条记录占一行。

以#开头的行为注释及空白行会被忽略。

一条记录由若干个空格或由制表符分隔的字段组成,如果字段用引号包围,那么它可以包含空白。

每条记录声明一种连接类型、一个客户端IP地址范围(如果和连接类型相关)、一个数据库名、一个用户 名字,以及对匹配这些参数的连接所使用的认证方法。

第一条匹配连接类型、客户端地址、连接请求的数据库名和用户名的记录将用于执行认证。如果选择了 一条记录而且认证失败,那么将不再考虑后面的记录;如果没有匹配的记录,访问将被拒绝。即从上向 下匹配,一旦匹配则不会再向下检查

每条记录可以是下面五种格式之一:

bash 复制代码
# local DATABASE USER METHOD [OPTIONS] 
# host DATABASE USER ADDRESS METHOD [OPTIONS] 
# hostssl DATABASE USER ADDRESS METHOD [OPTIONS] 
# hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] 
# hostgssenc DATABASE USER ADDRESS METHOD [OPTIONS] 
# hostnogssenc DATABASE USER ADDRESS METHOD [OPTIONS]

pg_hba.conf文件为pg实例的防火墙配置文件。配置文件格式分为5部分:

复制代码
TYPE DATABASE USER ADDRESS METHOD
  • 第1个字段只能是下面的取值。

    • local:这条记录匹配通过UNIX域套接字的连接认证。没有这种类型的记录,就不允许有UNIX 域套接字的连接。当pSql后面不指定主机名或IP地址时,即用UNIX域套接字的方式连接数据 库。

    • host:这条记录匹配通过TCP/IP进行的连接。包括了SSL和非SS的连接。

    • hostssI:这条记录匹配使用TCP/IP的SSL连接。必须是使用SSL加密的连接,且要使用这个选 项,编译服务器时必须打开SSL支持,启动服务器时必须打开SSL配置选项。

    • hostnossl:这条记录与hostssI相反,它只匹配那些在TCP/IP上不使用SSL的连接请求。

  • 第2个字段用于设置一个数据库名称,如果设置为al,表示可以匹配任何数据库,注意:如果设置为 replication时比较特殊,表示允许流复制连接,而不是允许连接到一个名为"replication"的数据库 上。

  • 第3个字段用于设置一个用户的名称,如果设置为all,表示可以匹配任何用户。

  • 第4个字段<ip/masklen>表示允许哪些IP地址来访问此服务器,如192.168.1.10/32表示只允许 192.168.1.10这台主机访问数据库,192.168.1.0/24表示IP地址前缀为192.168.1.X的主机都允许访 问数据库服务器。

  • 第5个字段表示验证方法,PostgreSQL支持的认证配置方式很多,最常用的认证方法是trust、 reject、md5和ident方法。

bash 复制代码
#METHOD有如下值可选 
md5:执行SCRAM-SHA-256或MD5身份验证加密密码来验证,是推荐使用的安全验证的方法 
peer:从操作系统获取客户端的操作系统用户名,并检查它是否与请求的数据库用户名匹配。这仅适用于本地 socket连接。 
trust:允许无条件连接,允许任何PostgresQL用户身份登录,而无需密码或任何其他身份验证。 
reject:拒绝任何条件连接,这对于从组中"过滤掉"某些主机非常有用。 
sCram-sha-256:执行SCRAM-SHA-256身份验证以验证用户的密码。 
password:要提供未加密的密码以进行身份验证。由于密码是通过网络以明文形式发送的,因此不建议使用 
gss:使用GSSAPI对用户进行身份验证,这仅适用于TCP/IP连接。 
sspi:使用sSPI对用户进行身份验证,这仅适用于windows。

ident:允许客户端上的特定操作系统用户连接到数据库。这种认证方式的使用场景是,客户端是主机上的某个 操作系统用户,已经通过了操作系统的身份认证,是数据库服务器可以信任的用户,不需要在数据库层面再次检 测身份。比如,如果配置了这种认证方式(配置中允许的用户名为dba)、这时在操作系统用户dba下,就能以 数据库用户dba的身份连接到数据库。服务器为了确定接收到的连接请求确实是客户端机器上的dba用户发起 的,而不是这台机器上其他用户发起的假冒请求,会向客户端机器上的ident服务发起请求,让ident服务查看 此TCP连接是否是dba用户发起的,如果不是,说明是假冒,则认证失败。如果客户端通过本地连接到服务器, 因为客户端与服务器在一台机器上,数据库服务器可以直接检查客户端用户的操作系统用户身份,就不需要向 ident服务发送请求进行判断了。 
1dap:使用LDAP服务器进行身份验证。 
radius:使用RADIUS服务器进行身份验证。 
cert:使用ssL客户端证书进行身份验证。 
pam:使用操作系统提供的可插入身份验证模块(PAM)服务进行身份验证。 
bsd:使用操作系统提供的BSD身份验证服务进行身份验证。

范例:

bash 复制代码
# pg_hba.conf 常用配置示例

##############################################################################
# 1、整机专用于数据库,无其他业务
# local all all trust
# 含义:本机上任意操作系统用户,可使用任意数据库用户(超级用户postgres)免密登录数据库
# 说明:主机只做数据库,禁用无用系统账号来保障安全
local   all     all             trust


##############################################################################
# 2、操作系统用户dba 和数据库用户dba,操作系统dba本机免密登录(ident对等认证)
# local  数据库  数据库用户        认证方式
local   all     dba             ident


##############################################################################
# 3、本机登录全部使用密码md5校验
local   all     all             md5


##############################################################################
# 4、所有远程地址全部使用md5密码验证
host    all     all             0.0.0.0/0        md5


##############################################################################
# 5、仅允许 10.0.0.0/24 网段远程访问,md5密码验证
# TYPE    DATABASE  USER    ADDRESS        METHOD
host    all       all     10.0.0.0/24     md5


##############################################################################
# 6、只允许数据库用户test,访问test数据库,任意远程地址md5登录
# TYPE    DATABASE  USER    ADDRESS        METHOD
host    test      test    0.0.0.0/0       md5
3.4.2打开远程连接

默认安装完的PG只能监听local,如果需要远程连接,需要监听对外提供服务的IP地址。

范例:实现远程连接

bash 复制代码
# 修改postgres用户密码
[postgres@localhost ~]$ psql
psql (18.4)
Type "help" for help.

postgres=# alter user postgres with password '123456';

# 查看监听地址和端口,默认为127.0.0.1:5432
[postgres@localhost ~]$ ss -ntl
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128        0.0.0.0:22                        0.0.0.0:*
LISTEN     0      200    127.0.0.1:5432                      0.0.0.0:*

# 修改postgresql.conf,开启外部监听
[postgres@localhost ~]$ vim /var/lib/pgsql/18/data/postgresql.conf
listen_addresses = '*'     # 将默认localhost修改为 * 或者 0.0.0.0

# 修改pg_hba.conf,增加远程访问规则
[root@localhost ~]# vim /var/lib/pgsql/18/data/pg_hba.conf
host    all     all     0.0.0.0/0        md5

# 重启服务使配置生效
[postgres@localhost ~]$ /usr/pgsql-18/bin/pg_ctl restart -mf

# 查看监听地址和端口
[postgres@localhost ~]$ ss -ntl
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128        0.0.0.0:22                        0.0.0.0:*

# 其他机器测试远程登录
[root@localhost ~]# psql -d postgres -h 192.168.108.155 -p 5432 -U postgres
Password for user postgres: 123456
psql (10.23, server 18.4)
WARNING: psql major version 10, server major version 18.
Some psql features might not work.
Type "help" for help.

postgres=#

范例:利用.pgpass文件实现免密密码连接远程posgresql

bash 复制代码
# 编辑 .pgpass 免密文件
[root@localhost ~]# vim .pgpass
# 格式:hostname:port:database:username:password
192.168.108.155:5432:postgres:postgres:123456

# .pgpass 权限必须为600,否则不生效
[root@localhost ~]# chmod 600 .pgpass

# 查看文件权限
[root@localhost ~]# ll .pgpass
-rw------- 1 root root 44 Jul 19 20:46 .pgpass

# -w 参数:强制不交互输入密码,读取.pgpass自动登录
[root@localhost ~]# psql -d postgres -h 192.168.108.155 -p 5432 -U postgres -w
psql (10.23, server 18.4)
WARNING: psql major version 10, server major version 18.
Some psql features might not work.
Type "help" for help.

postgres=# \c
psql (10.23, server 18.4)
WARNING: psql major version 10, server major version 18.
Some psql features might not work.
You are now connected to database "postgres" as user "postgres".

测试:使用笔记本测试

3.5常用操作

3.5.1查看psql帮助
bash 复制代码
#列出psql帮助用法 
help

#列出以\开头的命令,即psql的命令 
\?

#列出所有SQL命令的帮助,注意:SQL语句必须以;结束 
\h

#查看指定SQL的帮助 
\h create database 
\help create user

范例:

bash 复制代码
postgres=# help
You are using psql, the command‑line interface to PostgreSQL.
Type:
  \copyright for distribution terms
  \h for help with SQL commands
  \? for help with psql commands
  \g or terminate with semicolon to execute query
  \q to quit

postgres=# \?
General
  \copyright        show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab
  \errverbose       show most recent error message at maximum verbosity
  \g [FILE] or ;    execute query (and send results to file or |pipe)
  \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

postgres=# \h
Available help:
 ABORT           CLUSTER         CREATE VIEW         DROP USER MAPPING
 ALTER AGGREGATE COMMENT         DEALLOCATE          DROP VIEW
 ALTER COLLATION COMMIT          DECLARE             END
 ALTER CONVERSION COMMIT PREPARED DELETE            EXECUTE

postgres=# \h create user
Command:     CREATE USER
Description: define a new database role
Syntax:
CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

  SUPERUSER | NOSUPERUSER
  | CREATEDB | NOCREATEDB
  | CREATEROLE | NOCREATEROLE
  | INHERIT | NOINHERIT
  | LOGIN | NOLOGIN
  | REPLICATION | NOREPLICATION
  | BYPASSRLS | NOBYPASSRLS
  | CONNECTION LIMIT connlimit
  | [ ENCRYPTED ] PASSWORD 'password'
  | VALID UNTIL 'timestamp'
  | IN ROLE role_name [, ...]
  | IN GROUP role_name [, ...]
  | ROLE role_name [, ...]
  | ADMIN role_name [, ...]
  | USER role_name [, ...]
  | SYSID uid
3.5.2设置显示信息的格式
bash 复制代码
#后续查询将坚着显示,类似于MySQL中的\G 
\x

#开启命令执行时长提示 
\timing on

#显示详细的信息,可以打印出报出问题的源代码位置 
\set VERBOSITY verbose

范例:

bash 复制代码
postgres=# \x
Expanded display is on.

postgres=# \l
List of databases
-[ RECORD 1 ]-----+----------------------
Name              | postgres
Owner             | postgres
Encoding          | UTF8
Collate           | en_US.UTF-8
Ctype             | en_US.UTF-8
Access privileges |

-[ RECORD 2 ]-----+----------------------
Name              | template0
Owner             | postgres
Encoding          | UTF8
Collate           | en_US.UTF-8
Ctype             | en_US.UTF-8
Access privileges | =c/postgres
                  | postgres=CTc/postgres

-[ RECORD 3 ]-----+----------------------
Name              | template1
Owner             | postgres
Encoding          | UTF8
Collate           | en_US.UTF-8
Ctype             | en_US.UTF-8
Access privileges | =c/postgres
                  | postgres=CTc/postgres

postgres=# select pg_sleep(3);
-[ RECORD 1 ]
pg_sleep |

范例:

bash 复制代码
postgres=# \timing on 
Timing is on. 
postgres=# select pg_sleep(3); 
-[ RECORD 1 ] 
pg_sleep |

Time: 3004.184 ms (00:03.004)

范例:查看出错对应的源代码位置

bash 复制代码
postgres=# \set VERBOSITY verbose

postgres=# select gao; 
ERROR: 42703: column "gao" does not exist 
LINE 1: select gao;
               ^ 
LOCATION: errorMissingColumn, parse_relation.c:3827 
#说明:错误对应的是parse_relation.c文件中的3827行中errorMissingColumn函数
3.5.3数据库的创建和删除

创建数据库可以使用SQL语句create database实现,也可以利用createdb命令创建数据库

createdb是一个SQL命令CREATE DATABASE的封装。

createdb命令语法格式如下:

bash 复制代码
[postgres@localhost ~]$ createdb --help
createdb creates a PostgreSQL database.

Usage:
  createdb [OPTION]... [DBNAME] [DESCRIPTION]

Options:
  -D, --tablespace=TABLESPACE     default tablespace for the database
                                  # 指定数据库默认表空间
  -e, --echo                      show the commands being sent to the server
                                  # 将createdb生成的SQL打印出来
  -E, --encoding=ENCODING         encoding for the database
                                  # 指定数据库编码
  -l, --locale=LOCALE             locale settings for the database
                                  # 指定数据库语言环境
      --lc-collate=LOCALE         LC_COLLATE setting for the database
      --lc-ctype=LOCALE           LC_CTYPE setting for the database
      --builtin-locale=LOCALE     builtin locale setting for the database
      --icu-locale=LOCALE         ICU locale setting for the database
      --icu-rules=RULES           ICU rules setting for the database
      --locale-provider={builtin|libc|icu}
                                  locale provider for the database's default collation
  -O, --owner=OWNER               database user to own the new database
                                  # 指定数据库属主
  -S, --strategy=STRATEGY         database creation strategy wal_log or file_copy
  -T, --template=TEMPLATE         template database to copy
                                  # 指定创建数据库使用的模板库
  -V, --version                   output version information, then exit
  -?, --help                      show this help, then exit
                                  # 显示createdb帮助信息

Connection options:
  -h, --host=HOSTNAME             database server host or socket directory
                                  # 指定数据库主机地址
  -p, --port=PORT                 database server port
                                  # 指定数据库端口
  -U, --username=USERNAME         user name to connect as
                                  # 连接数据库用户名
  -w, --no-password               never prompt for password
                                  # 不交互提示输入密码
  -W, --password                  force password prompt
                                  # 强制提示输入密码
      --maintenance-db=DBNAME     alternate maintenance database

By default, a database with the same name as the current user is created.

Report bugs to <pgsql-bugs@lists.postgresql.org>.
PostgreSQL home page: <https://www.postgresql.org/>

删除数据库可以使用SQL语句dropdatabase实现

范例:创建数据库

bash 复制代码
#方法1 
[postgres@localhost ~]$ createdb -h localhost -p 5432 -U postgres testdb 
Password:123456

#方法2 
[postgres@localhost ~]$ psql 
psql (18.4) 
Type "help" for help.

postgres=# create database testdb;

范例:删除数据库

bash 复制代码
[postgres@localhost ~]$ psql 
psql (18.4) 
Type "help" for help.

postgres=# drop database testdb; 
DROP DATABASE

范例:查看数据库存放目录的路径

bash 复制代码
postgres=# select oid,datname from pg_database;
 oid |  datname
-----+-----------
   5 | postgres
   1 | template1
   4 | template0
(3 rows)

[postgres@localhost ~]$ ls /var/lib/pgsql/18/data/base/
1  4  5
3.5.4管理和查看模式

一个数据库包含一个或多个已命名的模式,模式又包含表。模式还可以包含其它对象,包括数据类型、 函数、操作符等。同一个对象名可以在不同的模式里使用而不会导致冲突;比如,schema1和schema2 都可以包含一个名为test的表

bash 复制代码
-- 创建模式语法
create schema schema_name;

-- 删除模式语法
drop schema schema_name;

# 列出所有schema
postgres=# \dn
List of schemas
  Name  |      Owner
--------+-------------------
 public | pg_database_owner
(1 row)

# 创建schema sch
postgres=# create schema sch;
CREATE SCHEMA

postgres=# \dn
List of schemas
  Name  |      Owner
--------+-------------------
 public | pg_database_owner
 sch    | postgres
(2 rows)

# 创建t1表,默认在public schema
postgres=# create table t1(id int);
CREATE TABLE

# public下已经存在t1,再次创建报错
postgres=# create table t1(id int);
ERROR:  relation "t1" already exists

# 在sch模式下创建同名t1表
postgres=# create table sch.t1(id int);
CREATE TABLE

# 默认搜索路径查看public下的表
postgres=# \dt
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | t1   | table | postgres
(1 row)

# 查看指定schema下的表
postgres=# \dt sch.t1
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 sch    | t1   | table | postgres
(1 row)
3.5.5查看和连接数据库
bash 复制代码
# 列出所有数据库名,相当于MySQL中的show databases;
postgres=# \l
List of databases
   Name    |  Owner   | Encoding | Locale Provider |   Collate   |    Ctype    | Locale | ICU Rules | Access privileges
-----------+----------+----------+-----------------+-------------+-------------+--------+-----------+-----------------------
 postgres  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           |
 template0 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres          +
           |          |          |                 |             |             |        |           | postgres=CTc/postgres
 template1 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres          +
           |          |          |                 |             |             |        |           | postgres=CTc/postgres
(3 rows)

# 创建一个数据库,观察下变化
postgres=# create database testdb;
CREATE DATABASE

# 再次查看
postgres=# \l
List of databases
   Name    |  Owner   | Encoding | Locale Provider |   Collate   |    Ctype    | Locale | ICU Rules | Access privileges
-----------+----------+----------+-----------------+-------------+-------------+--------+-----------+-----------------------
 postgres  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           |
 template0 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres          +
           |          |          |                 |             |             |        |           | postgres=CTc/postgres
 template1 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres          +
           |          |          |                 |             |             |        |           | postgres=CTc/postgres
 testdb    | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           |
(4 rows)

# 显示数据库详细信息,比如大小
postgres=# \l+
List of databases
   Name    |  Owner   | Encoding | Locale Provider |   Collate   |    Ctype    | Locale | ICU Rules | Access privileges |  Size   | Tablespace |                Description
-----------+----------+----------+-----------------+-------------+-------------+--------+-----------+-------------------+---------+------------+-------------------------------------------
 postgres  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           |                   | 7646 kB | pg_default | default administrative connection database
 template0 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres      +| 7489 kB | pg_default | unmodifiable empty database
           |          |          |                 |             |             |        |           | postgres=CTc/postgres |         |            |
 template1 | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           | =c/postgres      +| 7718 kB | pg_default | default template for new databases
           |          |          |                 |             |             |        |           | postgres=CTc/postgres |         |            |
 testdb    | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 |        |           |                   | 7561 kB | pg_default |
(4 rows)

# 查看当前连接信息
postgres=# \c
You are now connected to database "postgres" as user "postgres".

# 切换数据库,相当于MySQL use
postgres=# \c testdb
You are now connected to database "testdb" as user "postgres".

# 查看当前连接详细信息
testdb=# \conninfo
Connection Information
      Parameter       |      Value
----------------------+-----------------
 Database             | testdb
 Client User          | postgres
 Socket Directory     | /run/postgresql
 Server Port          | 5432
 Options              |
 Protocol Version     | 3.0
 Password Used        | false
 GSSAPI Authenticated | false
 Backend PID          | 1972
 SSL Connection       | false
 Superuser            | on
 Hot Standby          | off
(12 rows)
3.5.6 管理表

PostgreSQL支持多种数据类型实现表结构的创建

范例:查看支持数据类型

bash 复制代码
testdb=# select typname from pg_type;
                  typname
----------------------------------------
 bool
 bytea
 char
 name
 int8
 int2
 int2vector
 int4
 regproc
 text
 oid
 tid
 xid
 cid
 oidvector
 pg_type
 pg_attribute
 pg_proc
 pg_class
 json
 xml
 ......
(621 rows)

范例:管理表

bash 复制代码
testdb=# \c testdb
You are now connected to database "testdb" as user "postgres".

testdb=# create table tb1 (id serial primary key,name text);
CREATE TABLE

testdb=# insert into tb1 (name) select (md5(random()::text)) from generate_series (2,10);
INSERT 0 9

testdb=# select * from tb1;
 id |               name
----+----------------------------------
  1 | 4534485a0d2517117a8848ad869b15bb
  2 | b206a46cd9beca36fdad1dd651723d65
  3 | a7126c510f91184d694d8e3f06bd0c3a
  4 | 1b5e08e3046cea04f2157caec1594724
  5 | 99d882abb4823d4fdd5d7f9081382532
  6 | 3d5cc2b18c8aacf0170e674ed20cb249
  7 | 5f8909d5ce6241f4fe01734bd140f044
  8 | de397cee8c6746b7b61f1956e5597a52
  9 | ec41e0a9c28e51af59c1ace7635b9471
(9 rows)

# PostgreSQL中插入100万条记录观察耗时
testdb=# \timing on
Timing is on.

testdb=# insert into tb1 (name) select (md5(random()::text)) from generate_series (1,1000000);
INSERT 0 1000000
Time: 13892.772 ms (00:13.893) # 13秒

# 复制表结构,不复制数据
testdb=# create table tb2 (like tb1);
CREATE TABLE

testdb=# \d tb2
                      Table "public.tb2"
 Column |  Type   | Collation | Nullable | Default
--------+---------+-----------+----------+---------
 id     | integer |           | not null |
 name   | text    |           |          |

testdb=# select * from tb2;
 id | name
----+------
(0 rows)

Time: 1.141 ms

testdb=# drop table tb2;
DROP TABLE
3.5.7查看表和表信息
bash 复制代码
#列出所有表,视图,序列
testdb=# \d
List of relations
 Schema |    Name    |   Type   |  Owner
--------+------------+----------+----------
 public | tb1        | table    | postgres
 public | tb1_id_seq | sequence | postgres
(2 rows)

#列出public schema中所有的表名,相当于show tables;
testdb=# \dt
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | tb1  | table | postgres
(1 row)

#查看tb1的表信息
testdb=# \dt tb1
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | tb1  | table | postgres
(1 row)

#支持通配符*和?,以下显示所有t开头的表
testdb=# \dt t*
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | tb1  | table | postgres
(1 row)

#列出sch模式的表结构
testdb=# create schema sch;
testdb=# create table sch.t1(id int);

testdb=# \dt sch.*
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 sch    | t1   | table | postgres
(1 row)

#查看表结构,相当于MySQL desc
testdb=# \d tb1
                      Table "public.tb1"
 Column |  Type   | Collation | Nullable |             Default
--------+---------+-----------+----------+----------------------------------
 id     | integer |           | not null | nextval('tb1_id_seq'::regclass)
 name   | text    |           |          |
Indexes:
    "tb1_pkey" PRIMARY KEY, btree (id)

#列出所有表信息,包括大小
testdb=# \dt+
List of tables
 Schema | Name | Type  |  Owner   | Persistence | Access method | Size  | Description
--------+------+-------+----------+-------------+---------------+-------+-------------
 public | tb1  | table | postgres | permanent   | heap          | 65 MB |
(1 row)

#列出tb1表信息
testdb=# \dt tb1
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | tb1  | table | postgres
(1 row)

#列出tb1表大小信息
testdb=# \dt+ tb1
List of tables
 Schema | Name | Type  |  Owner   | Persistence | Access method | Size  | Description
--------+------+-------+----------+-------------+---------------+-------+-------------
 public | tb1  | table | postgres | permanent   | heap          | 65 MB |

#查看pg_tables系统视图
testdb=# select * from pg_tables;
 schemaname |        tablename         | tableowner | tablespace | hasindexes | hasrules | hastriggers | rowsecurity
------------+--------------------------+------------+------------+------------+----------+-------------+-------------
 pg_catalog | pg_statistic             | postgres   |            | t          | f        | f           | f
 pg_catalog | pg_type                  | postgres   |            | t          | f        | f           | f
 public     | tb1                      | postgres   |            | t          | f        | f           | f
 pg_catalog | pg_foreign_table         | postgres   |            | t          | f        | f           | f
 pg_catalog | pg_authid                | postgres   | pg_global  | t          | f        | f           | f
 sch        | t1                       | postgres   |            | f          | f        | f           | f
 pg_catalog | pg_statistic_ext_data    | postgres   |            | t          | f        | f           | f
 pg_catalog | pg_user_mapping          | postgres   |            | t          | f        | f           | f
 ......

#查看表总大小(表+索引+toast)
testdb=# select pg_total_relation_size('tb1');
 pg_total_relation_size
------------------------

(1 row)

testdb=# select pg_total_relation_size('tb1')/1024/1024||'MB';
 ?column?
----------
 86MB
(1 row)

范例:查看表对应的文件径

bash 复制代码
postgres=# \c testdb
You are now connected to database "testdb" as user "postgres".

testdb=# select oid,datname from pg_database where datname = 'testdb';
 oid  | datname
------+---------
16402 | testdb
(1 row)

testdb=# select relid from pg_stat_all_tables where relname='t1';
 relid
-------

(1 row)

testdb=# \q

[postgres@localhost ~]$ ll /var/lib/pgsql/18/data/base/16402/16431
-rw------- 1 postgres postgres 0 Jul 26 11:14 /var/lib/pgsql/18/data/base/16402/16431
3.5.8表的CRUD

SQL的CRUD,即 Insert,update,delete,select四条语句范例:

bash 复制代码
# 清空环境
postgres=# \c testdb;
You are now connected to database "testdb" as user "postgres".

testdb=# drop table tb1;
DROP TABLE

# 创建表tb1
testdb=# create table tb1 (id serial,name varchar(10));
CREATE TABLE

# 查看有哪些表
testdb=# \dt
List of tables
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | tb1  | table | postgres
(1 row)

# 查看tb1表结构
testdb=# \d tb1;
                          Table "public.tb1"
 Column |         Type          | Collation | Nullable |                  Default
--------+-----------------------+-----------+----------+-------------------------------------------
 id     | integer               |           | not null | nextval('tb1_id_seq'::regclass)
 name   | character varying(10) |           |          |

# 向tb1表插入数据
testdb=# insert into tb1(name)values('gao');
INSERT 0 1

testdb=# insert into tb1(name)values('zhang');
INSERT 0 1

#验证插入的数据
testdb=# select * from tb1;
 id |  name
----+--------
  1 | gao
  2 | zhang

# 更新tb1表中id为2的name为ma
testdb=# update tb1 set name='ma' where id=2;
UPDATE 1

#验证改了没
testdb=# select * from tb1;
 id | name
----+------
  1 | gao
  2 | ma
(2 rows)

# 删除tb1表中id为2的数据
testdb=# delete from tb1 where id=2;
DELETE 1

#验证删除了没
testdb=# select * from tb1;
 id | name
----+------
  1 | gao
(1 row)

#清空表
testdb=# truncate tb1;
TRUNCATE TABLE

testdb=# truncate table tb1;
TRUNCATE TABLE

testdb=# select * from tb1;
 id | name
----+------
(0 rows)
3.5.9索引管理

范例:创建和删除索引

bash 复制代码
testdb=# create table tb1(id int,info text,crt_time timestamp);
CREATE TABLE

testdb=# insert into tb1 select generate_series(1,1000000),md5(random()::text),clock_timestamp();
INSERT 0 1000000

testdb=# select * from tb1 limit 3;
 id |               info                |          crt_time
----+----------------------------------+----------------------------
  1 | 67d6285a42ba94dedd86048a0008683d | 2026-07-26 20:34:26.141821
  2 | c59be31fca89ae637ed6ce4cff13e141 | 2026-07-26 20:34:26.142127
  3 | 60bfbd9412a4b788901d70edff428255 | 2026-07-26 20:34:26.142133
(3 rows)

# 创建索引
testdb=# create index idx_tb1_id on tb1(id);
CREATE INDEX

testdb=# \d tb1
                                  Table "public.tb1"
  Column  |            Type             | Collation | Nullable | Default
----------+-----------------------------+-----------+----------+---------
 id       | integer                     |           |          |
 info     | text                        |           |          |
 crt_time | timestamp without time zone |           |          |
Indexes:
    "idx_tb1_id" btree (id)

#删除索引
testdb=# drop index idx_tb1_id;
DROP INDEX

testdb=# \d tb1
                                  Table "public.tb1"
  Column  |            Type             | Collation | Nullable | Default
----------+-----------------------------+-----------+----------+---------
 id       | integer                     |           |          |
 info     | text                        |           |          |
 crt_time | timestamp without time zone |           |          |

范例:使用索引

bash 复制代码
#打开时间
testdb=# \timing on
Timing is on.

# 创建索引
testdb=# create index idx_tb1_id on tb1(id);

# 查询条件是索引列
testdb=# explain analyze select * from tb1 where id = 99999;
                                                         QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Index Scan using idx_tb1_id on tb1  (cost=0.42..8.44 rows=1 width=45) (actual time=0.030..0.032 rows=1.00 loops=1)
   Index Cond: (id = 99999)
   Index Searches: 1
   Buffers: shared hit=4
 Planning Time: 0.099 ms
 Execution Time: 0.054 ms
(6 rows)

Time: 0.777 ms

#查询条件不是索引列
testdb=# explain analyze select * from tb1 where info ='67d6285a42ba94dedd86048a0008683d';
                                                              QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..15554.43 rows=1 width=45) (actual time=0.283..31.611 rows=1.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=9346
   ->  Parallel Seq Scan on tb1  (cost=0.00..14554.33 rows=1 width=45) (actual time=15.751..25.377 rows=0.33 loops=3)
         Filter: (info = '67d6285a42ba94dedd86048a0008683d'::text)
         Rows Removed by Filter: 333333
         Buffers: shared hit=9346
 Planning Time: 0.079 ms
 Execution Time: 31.634 ms
(10 rows)

Time: 32.308 ms

#关闭索引扫描(会话级别,仅用于测试,不要在线上使用)
testdb=# set enable_indexscan=off;
SET
Time: 0.487 ms

testdb=# set enable_bitmapscan=off;
SET
Time: 0.363 ms

# 再次查询,强制走并行全表扫描
testdb=# explain analyze select * from tb1 where id = 99999;
                                                              QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..15554.43 rows=1 width=45) (actual time=18.017..20.143 rows=1.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=9346
   ->  Parallel Seq Scan on tb1  (cost=0.00..14554.33 rows=1 width=45) (actual time=10.684..15.061 rows=0.33 loops=3)
         Filter: (id = 99999)
         Rows Removed by Filter: 333333
         Buffers: shared hit=9346
 Planning Time: 0.087 ms
 Execution Time: 20.167 ms
(10 rows)

Time: 21.092 ms
3.5.10表空间
bash 复制代码
#列出所有表空间,实际上PostgreSQL中的表空间就是对应一个目录,放在这个表空间的表,就是把表的数据文件放到这个表空间下。
testdb=# \db
List of tablespaces
    Name    |  Owner   | Location
------------+----------+----------
 pg_default | postgres |
 pg_global  | postgres |
(2 rows)

testdb=# select * from tb1;
   id    |               info                |          crt_time
---------+----------------------------------+----------------------------
       1 | 67d6285a42ba94dedd86048a0008683d | 2026-07-26 20:34:26.141821
       2 | c59be31fca89ae637ed6ce4cff13e141 | 2026-07-26 20:34:26.142127
       3 | 60bfbd9412a4b788901d70edff428255 | 2026-07-26 20:34:26.142133
       4 | 9b20c15670378a9a52e44e57bbcccc3a | 2026-07-26 20:34:26.142142
......

testdb=# copy tb1 to '/tmp/tb1.txt';
COPY 1000000
Time: 299.741 ms

[postgres@localhost ~]$ cat /tmp/tb1.txt | wc -l

范例:表空间pg_tblspc目录

bash 复制代码
[postgres@localhost ~]$ mkdir ts1

testdb=# create tablespace ts1 location '/var/lib/pgsql/ts1';
CREATE TABLESPACE

testdb=# \db
List of tablespaces
    Name    |  Owner   |      Location
------------+----------+--------------------
 pg_default | postgres |
 pg_global  | postgres |
 ts1        | postgres | /var/lib/pgsql/ts1
(3 rows)

[postgres@localhost ~]$ readlink /var/lib/pgsql/18/data/pg_tblspc/32781
/var/lib/pgsql/ts1
3.5.11查看系统信息

可以通过系统函数查看系统信息,也可以通过show/set查看和修改配置

bash 复制代码
# 查看版本信息
testdb=# select version();
                                                                 version
--------------------------------------------------------------------------------------------------------
 PostgreSQL 18.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-28), 64-bit
(1 row)

#查看数据库启动时间
testdb=# select pg_postmaster_start_time();
        pg_postmaster_start_time
-------------------------------------
 2026-07-26 20:26:47.209345+08
(1 row)

#重载配置文件
[postgres@localhost ~]$ pg_ctl reload
server signaled

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

postgres=# select pg_conf_load_time();
         pg_conf_load_time
-------------------------------------
 2026-07-26 21:30:34.496232+08
(1 row)

#查看时区
postgres=# show timezone;
   TimeZone
---------------
 Asia/Shanghai
(1 row)

#会话临时修改时区
postgres=# set timezone='Asia/Shanghai';
SET

#永久修改时区,修改postgresql.conf
[postgres@localhost ~]$ vim /var/lib/pgsql/18/data/postgresql.conf
783 timezone = 'Asia/Shanghai'

#重载配置生效
[postgres@localhost ~]$ pg_ctl reload
server signaled

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

postgres=# select now();
               now
-------------------------------------
 2026-07-26 21:34:15.716666+08
(1 row)

#查看当前用户
postgres=# select user;
   user
----------
 postgres
(1 row)

postgres=# select current_user;
 current_user
--------------
 postgres
(1 row)

postgres=# select session_user;
 session_user
--------------
 postgres
(1 row)

#查看当前数据库
postgres=# \c testdb
You are now connected to database "testdb" as user "postgres".

testdb=# select current_database();
 current_database
------------------
 testdb
(1 row)

#查看指定参数
testdb=# show port;
 port
------

(1 row)

testdb=# show archive_mode;
 archive_mode
--------------
 off
(1 row)

#查看全部参数
postgres=# show all;
                 name                  |             setting             |                                        description
---------------------------------------+---------------------------------+-------------------------------------------------------------------------------------------
 allow_alter_system                    | on                              | Allows running the ALTER SYSTEM command.
 allow_in_place_tablespaces            | off                             | Allows tablespaces directly inside pg_tblspc, for testing.
 allow_system_table_mods               | off                             | Allows modifications of the structure of system tables.
 application_name                      | psql                            | Sets the application name to be reported in statistics and logs.
 archive_cleanup_command               |                                 | Sets the shell command that will be executed at every restart point.
 archive_command                       | (disabled)                      | Sets the shell command that will be called to archive a WAL file.

#会话级别修改参数
postgres=# set maintenance_work_mem to '128MB';
SET

postgres=# show maintenance_work_mem;
 maintenance_work_mem
----------------------
 128MB
(1 row)

范例:explain可以查看SQL执行的计划

explain :只输出执行计划,不会真实执行 SQL;

explain analyze :真实执行语句,拿到真实时间与 buffer 统计。

bash 复制代码
#explain可以查看SQL执行的计划
postgres=# explain select * from t1;
                        QUERY PLAN
------------------------------------------------------
 Seq Scan on t1  (cost=0.00..35.50 rows=2550 width=4)
(1 row)

postgres=# explain analyze select * from t1;
                                                         QUERY PLAN
------------------------------------------------------------------------------------------
 Seq Scan on t1  (cost=0.00..35.50 rows=2550 width=4) (actual time=0.008..0.008 rows=0.00 loops=1)
 Planning Time: 0.045 ms
 Execution Time: 0.022 ms
(3 rows)

postgres=# explain analyze verbose select * from t1;
                                                              QUERY PLAN
-----------------------------------------------------------------------------------------------
 Seq Scan on public.t1  (cost=0.00..35.50 rows=2550 width=4) (actual time=0.009..0.009 rows=0.00 loops=1)
   Output: id
 Planning Time: 0.045 ms
 Execution Time: 0.027 ms
(4 rows)

3.6安装使用图形化工具pgadmin

3.6.1 pgadmin 介绍

pgAdmin是一个免费的开源图形数据库管理工具,用于管理PostgreSQL和行生的关系数据库,如 EnterpriseDB的EDB Advanced Server。pgAdmin可以以两种模式安装:服务器模式和桌面模式。服务 器模式下的pgAdmin可以部署在不同的Web服务器中,如:Apache,Nginx等

pgAdmin是一个在PostgreSQL许可下发布的免费软件项目。该软件可从PostgreSQL镜像网络以源代码 和二进制格式获得。因为从源代码编译比较繁琐,建议尽可能使用安装二进制包。

pgAdmin 4是对 pgAdmin 的完全重写,使用 Python和Javascript/jQuery构建

官网:https://www.pgadmin.org/

3.6.2安装pgadmin

配置中文

连接pgsql

连接成功

相关推荐
重生的黑客16 小时前
Linux 进程程序替换与自定义 Shell:从 exec 函数族到命令行解释器
linux·运维·服务器·shell
北极糊的狐16 小时前
阿里云服务器-命令2-Linux 系统实时资源监视器 top 命令详解(进程级实时资源监控)
linux·运维·服务器
三言老师17 小时前
clear与history历史命令管理实操
linux·运维·服务器·网络·centos
味悲17 小时前
Linux 环境下 DNS 服务器搭建
linux·运维·服务器
greenbbLV17 小时前
中小公司积分商城选型:SaaS与私有化优劣对比分析
大数据·运维·人工智能
feasibility.18 小时前
wsl安装Ubuntu方法(含网络不稳定处理)
linux·运维·windows·ubuntu
汽车网络安全爱好者18 小时前
Public Key Infrastructure(二)— 深入理解 X.509 证书:从 RFC 5280 到 OpenSSL 实践
运维·服务器·算法·网络安全·汽车·密码学·可信计算技术
粗体鱼18 小时前
RAG/Agent 记忆混合检索多路召回:RRF 算法与Chunk RRF、Document RRF如何决策TopK
postgresql·milvus·es·rag·rff·mermory
落叶飘飘s19 小时前
彩笔运维勇闯机器学习--梯度下降法
运维·人工智能·机器学习
若衹如初見19 小时前
介绍了LiveBindings格式化的几种进阶方法: * 使用表达式列格式化。 * 自定义绑定方法。 * 使用自定义表单方法格式化。 ...
运维·服务器·前端