PostgreSQL常用的内置函数

更多关于DB管理的函数在chapter 9 函数和操作符

查询当前事务的xid

select txid_current();
select pg_backend_pid();

查询表元组的xmax,xmin,ctid

select xmin,xmax,ctid from tabname where id=xx;

查询数据库对象的oid(db,表)

select relname,oid from pg_class where relname='relname';
select oid,datname from pg_database where datname='dbname';

查询列信息

select data_type from information_schema.columns where table_schema= 'public'  and table_name= 'test' and column_name= 'name';

generate_series函数使用

generate_series(start,stop)                --int or bigint
generate_series(start,stop,step)           --int or bigint
generate_series(start,stop, step interval) --timestamp or timestamp with time zone

select generate_series(1,10);
select generate_series(1,10,3);
select generate_series(5,1);
select generate_series(5,1,-1);

select generate_series(now(),now() + '7 day','1 day');
select generate_series(to_date('20120827','yyyymmdd'),to_date('20120828','yyyymmdd'),'3 h');


create table t_kenyon(id int,ip_start inet,ip_end inet);
insert into t_kenyon values(1,'192.168.1.254','192.168.2.5');

查询当前数据库的锁关系

select * from pg_locks;
    
select a.locktype,a.database,a.pid,a.mode,a.relation,b.relname
from pg_locks a
join pg_class b on a.relation = b.oid
where upper(b.relname) = 'TABLE_NAME';

select usename,current_query ,query_start,procpid,client_addr from pg_stat_activity 
where procpid=17509;

ps -ef|grep 17509
kill -9 17509

常用快捷命令

l [dbname]
d [tablename]
x #更改显示方式
q #退出当前环境
i filename.sql #执行sql文件
psql -d dbname -f xxx.sql
s filename.txt #历史命令
set autocommit on|off
set transaction isolation read commited | repeated read | serializable

批量插入SQL语句

postgres=# insert into tbl1(id,info,crt_time) select generate_series(1,10000),'test',now();
postgres=# insert into tbl1(id,info,crt_time) values(1,'test',now()),(2,'test',now()),(3,'test',now());

postgres=# begin;    
postgres=# insert into tbl1 (id,info,crt_time) values (1,'test',now()); 
postgres=# select id,generate_series(0,ip_end-ip_start)+ip_start as ip_new from t_kenyon; 

test03=# d test  
                Table "public.test"  
  Column  |            Type             | Modifiers   
----------+-----------------------------+-----------  
 id       | integer                     | not null  
 info     | text                        |   
 crt_time | timestamp without time zone |   
Indexes:  
    "test_pkey" PRIMARY KEY, btree (id)  
  
test=# copy test from stdin;  
>> 8    'test'  '2017-01-01'  
>> .  
COPY 2  

修改用户口令

alter user postgres with password 'new password';

操作日志

postgresql.conf中log_min_duration_statement设为0,可以实现记录所有操作日志
原文地址:https://www.cnblogs.com/bingo711x/p/6733394.html