PostgreSQL常用命令

PostgreSQL性能不错,在部分场景下还可以弥补MySQL的不足,但是由于sql语法和mysql有较大的区别,而且增加了很多特性,所以稍微有一些学习成本。

更多PG的使用可以参考 PG手册

连接数据库

1
>  psql -h localhost -p 32770 -d postgres -U postgres

数据库相关命令

1
2
3
4
5
6
7
8
9
10
11
12
13
-- 列出所有数据库
postgres=# \l

-- 创建数据库
postgres=# create database test;

-- 切换数据库
postgres=# \c test;

-- 删除数据库
postgres=# drop database test;

-- 删除数据库时可能会报错: database "test" is being accessed by other users

schema相关命令

1
2
3
4
5
6
7
8
9
10
11
-- 创建schema
postgres=# \c create schema schema_name;

-- 列出当前库下所有schema
postgres=# \dn+

-- 或者用sql查询当前库下所有schema
postgres=# select * from information_schema.schemata;

-- 删除schema
postgres=# drop schema schema_name;

表相关命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-- 创建表
postgres=# create table schema_name.table_name(
id int primary key not null,
name varchar(100)
);

-- 查询库中所有表
postgres=# \dt+ *.*

-- 查询某个schema下的表
postgres=# \dt+ schema_name.*

-- 查看表结构信息
postgres=# \d schema_name.table_name;

-- 查看索引
postgres=# \di index_name;