select * from device where types::jsonb @>'[2,1]'::jsonb; '1' in(select json_array_elements_text(‘[1,2,4]'))
select base.*,(select json_array_elements_text(base.publishing_platform_list)) from documentation as base where '1'::varcharin(select json_array_elements_text(base.publishing_platform_list))
INSERTINTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';
方式2–生成新表时同时填充查询结果
命令:CREATE TABLE AS:从一条查询的结果中定义一个新表
示例:创建一个只包含表films中最近的记录的新表films_recent:
CREATETABLE films_recent AS SELECT * FROM films WHERE date_prod >= '2002-01-01';
注意:若添加参数TEMP,则表示生成临时表
统计磁盘占用
统计数各据库占用磁盘大小
SELECT d.datname ASName, pg_catalog.pg_get_userbyid(d.datdba) AS Owner, CASEWHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT') THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname)) ELSE'No Access' ENDASSIZE FROM pg_catalog.pg_database d ORDERBY CASEWHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT') THEN pg_catalog.pg_database_size(d.datname) ELSENULL ENDDESC-- nulls first LIMIT20
-- MISSING INDICES SELECT relname AS"Table name", usage_percentage "Indices usage overall scans" FROM ( SELECT relname, round(idx_scan * 100.0 / NULLIF(idx_scan + seq_scan, 0), 2) AS usage_percentage, (seq_scan + idx_scan) / avg(seq_scan + idx_scan) OVER () AS overall_percentage FROM pg_stat_user_tables tbl ) tbl WHERE usage_percentage < 90 AND overall_percentage > 0.01 ORDERBY usage_percentage DESC;
查看并删除PGSQL锁
SELECT locker.pid, pc.relname, locker.mode, locker_act.application_name, least(query_start,xact_start) start_time, locker_act.state, CASE WHEN granted='f'THEN 'wait_lock' WHEN granted='t'THEN 'get_lock' END lock_satus,current_timestamp - least(query_start,xact_start) AS runtime, locker_act.query FROM pg_locks locker,pg_stat_activity locker_act, pg_class pc WHERE locker.pid=locker_act.pid ANDNOT locker.pid=pg_backend_pid() AND application_name<>'pg_statsinfod' AND locker.relation = pc.oid AND pc.reltype<>0--and pc.relname='t' ORDERBY runtime desc;
select pid from pg_locks where relation in (selectoidfrom pg_class where relname='user_member') --取消后台操作,回滚未提交事物 select PG_CANCEL_BACKEND('2872’); --中断session,回滚未提交事物 select pg_terminate_backend(2872);
数据库占用连接
查看连接
-- 数据库占用连接 select * from pg_stat_activity where datname='device';
主动关闭连接
--pid为pg_stat_activity 中的字段 select pg_terminate_backend(pid) --可以配合查看链接sql进行使用 select pg_terminate_backend(pid) from pg_stat_activity where datname = 'xxx'
查看配置
select * from pg_settings -- 超时相关 select * from pg_settings wherenamelike'%timeout%'