postgresql常用命令
退出命令交互:
\q
删除索引:
drop index indexName
添加新字段:
alter table table_name add column column_name type datatype;
添加新字段不允许为null
alter table table_name add column_name type datatype not null;
添加新字段并且设置默认值
alter table table_name add column_name type datatype set default expressions;
修改已有字段名:
alter table table_name rename old_name to new _name;
修改已有字段类型:
alter table table_name alter column column_name type type_name;
删除字段
alter table table_name drop column column_name;
更改表的名字
alter table table_name rename to new_name;
显示所有表
\l
查看表的接口
\d tablename
扩展后续sql显示纵向显示
\x
mybatis保持原始符号
<![CDATA[ <= ]]>
导出表的数据(同时会导出表的创建语句)
pg_dump -h host -p port -U username -d database -t tablename > export path and file
./pg_dump -h 127.0.0.1 -p 5554 -U username -d databasename -t tablename -a > /var/config.sql
导出表的数据(仅仅导出数据,以insert的语句格式)
--inserts 导出insert语句
-a 仅仅导出数据
pg_dump -h host -p port -U username -d database -t database -a --inserts > export path and file
./pg_dump -h 127.0.0.1 -p 5554 -U username -d database -t database -a --inserts > /var/vul_history.sql
导入数据
psql -d databaename(数据库名) -U username(用户名) -f < 路径/文件名.sql // sql 文件不在当前路径下
配置客户端连接免密
(有问题,应该保存在环境变量配置中)
设置环境变量 PGPASSWORD
export PGPASSWORD youpassword
查看表的大小(不包含索引)
select pg_size_pretty(pg_relation_size('slave'));
select pg_size_pretty(pg_relation_size('表名'));
非阻塞创建索引
create index concurrently idx_table_name_x1 on table_name(col_name);
通常在postgresql创建普通索引如下
create index idx_table_name_x1 on table_name(col_name);
执行后在创建索引期间会阻塞 dml,如果是在比较繁忙的系统或者大表上执行该语句的话,估计很快就会有人问候你了。
所以应该使用 concurrently 参数: create index concurrently idx_table_name_x1 on table_name(col_name);
非阻塞创建不存在的索引
create index concurrently if no exists xxx_index_name on xxx_table_name (col1, col2);
create index concurrently if not exists vw_etl_sqms_task_runlog_task_name_status_index on vw_etl_sqms_task_runlog (task_name, status);
查看表的索引
select * from pg_indexes where tablename= 'meta_cicd_deploy';
查看执行计划
explain
切割字符串:
字符: vt2/test 结果: vt2 split_part(str, parttern, index)
SELECT count(DISTINCT split_part(images , '/', 1)) mages from docker_images_new;
导出表中的数据
\copy (sql query)) to '/home/123.csv' with (format csv);
\copy (select * from meta_maven where create_time > '2021-12-01 00:00:00' and create_time < '2021-12-30 00:00:00' and creator in ( 'v_pa011_sqms_alm', 'paic_deploy')) to '/home/123.csv' with (format csv);
时间字段格式化
to_char(created_date, 'yyyy-MM-dd')
select count(1), to_char(created_date, 'yyyy-MM-dd') from scenes_run_record group by to_char(created_date, 'yyyy-MM-dd') order by to_char(created_date, 'yyyy-MM-dd') desc ;