PostgreSQL 使用技巧

官方文档

随机查询

用随机函数的值来排序,以达到随机查询的目的;最好限制一个取数范围,不然对行数比较多的表来说,随机取数查询可能耗时会比较长。

PostgreSQL
select * fro some_table order by random() limit 100;
解决JPA不支持PostgreSQL双冒号的问题

冒号在JPA中是特殊符号,所以需要加转义字符

PostgreSQL
select * from some_table where details::varchar like 'ABC%';

Java中添加转义字符:

Java
String strSql = "select * from some_table where details\\:\\:varchar like 'ABC%'";
长事务的查询与中断
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 查询
SELECT
pid,
datname AS db,
query_start AS start,
now() - query_start AS lap,
query
FROM pg_stat_activity
WHERE state <> 'idle' and query not like '%pg_stat_activity%'
and (now() - query_start) > interval '10 seconds';

# 取消(pid为前面查询的具体值)
select pg_cancel_backend($pid);

# 中断
select pg_terminate_backend($pid);