一文全面了解PostgreSQL常用命令

213阅读模式

服务

  • 启动
pg_ctl start -D /usr/local/var/postgres
  • 暂停
pg_ctl stop -D /usr/local/var/postgres
  • 确认服务状态
ps aux | grep postgres

查看版本

  postgres --version

显示帮助

 psql --help

连接

  • 连接默认数据库:postgre
psql -d postgres
  • 连接指定数据库
psql -d 数据库名
  • 连接数据库并指定连接用户
psql -d 数据库名 -U 用户名
  • 退出
\q

数据库

  • 创建数据库
create database 数据库名;
  • 删除数据库
drop database 数据库名;
  • 显示数据库列表
\l
  • 选择数据库
\c 数据库名

用户

  • 创建用户
create user 用户名;
  • 给用户赋予权限:示例赋予最大权限
grant all privileges on database 数据库名 to 用户名;
  • 用户列表
\du
  • 赋予指定权限
grant select, insert, update, delete on 表名 to 用户名;
  • 删除指定权限
revoke select, insert, update, delete on 表名 from 用户名;

Schema

  • 创建Schema
create schema <schema_name>;
  • 确认当前的Schema
 select current_schema;
  • Schema列表
\dn

  • 显示表的列表
\dt
  • 显示指定表
\d 表名
  • 显示指定表的数据
select * from 表名
  • 按指定列排序显示数据
    • 默认:从小到大、从大到小,指定desc
select * from 表名 order by 列名
  • 修改表的owner
alter table 表名 owner to owner名;
  • 常规的DML操作:略

表结构修改

  • 添加列
alter table 表名 add 列名 数据类型;
  • 删除列
alter table 表名 drop 列名;
  • 列名变更
alter table 表名 rename 列名 to 新列名;
  • 改变列数据类型
alter table 表名 alter 列名 type 数据类型;

索引

  • 创建索引
create index 索引名 on 表名(列名);
  • 删除索引
drop index 索引名;

视图

  • 创建视图
create view 视图名 as 视图对应的语句;
  • 显示视图列表
\dv
  • 使用视图
select * from 视图名;
  • 删除视图
drop view 视图名;

读入外部SQL文件

 \i 文件名
文章源自懂站帝-http://www.sfdkj.com/13613.html
懂站帝
  • 本文由 发表于 2022年6月3日 08:42:32
  • 版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至395045033@qq.com举报,一经查实,本站将立刻删除。
评论  0  访客  0