文章转载自公众号:DB印象 作者:Aken
本次阅读时长:
![05e1a2a3cb314a0f9b3b37d37d612505.gif](https://img-blog.csdnimg.cn/img_convert/05e1a2a3cb314a0f9b3b37d37d612505.gif)
.
![504d2825b3f53eb7b6a0812c4090a1f8.gif](https://img-blog.csdnimg.cn/img_convert/504d2825b3f53eb7b6a0812c4090a1f8.gif)
.
事务设计规范
高并发场景,有时候会看到开发同学将很长的事务逻辑放在一个事务里面实现,其实这样对数据库并不友好。
我们应尽量避免单个事务过大、过长、过于复杂,建议将单个事务中多条SQL操作,分解、拆分,或者不放在同一个事务里,让每个事务的粒度尽可能小,这样可以尽量lock较少的资源,减少lock阻塞、dead lock的产生。
#sesseion1把所有数据都更新而不提交,一下子锁了2000千万条记录postgres=# begin;BEGINpostgres=# update tab_pgsql_main set mc='tab_pgsql_1.3';UPDATE 200000000#sesseion2 等待postgres=# update tab_pgsql_main set mc='tab_pgsql_1.4' where id=1;#sesseion3 等待postgres=# update tab_pgsql_main set mc='tab_pgsql_1.5' where id=2;如果#sesseion1分布批更新的话,则session2和session3中就能部分提前完成,这样可以避免大量的锁等待和出现大量的session占用系统资源,在做全表更新时请使用这种方法来执行。如下所示:postgres=# begin;BEGINpostgres=# update tab_pgsql_main set mc='tab_pgsql_1.3' where id>0 and id <=100000;UPDATE 100000postgres=#COMMIT;postgres=# begin;BEGINpostgres=# update tab_pgsql_main set mc='tab_pgsql_1.3' where id>100000 and id <=200000;UPDATE 100000postgres=#COMMIT;
Index索引设计规范
建议对频繁update,delete的index字段,用create index CONCURRENTLY,drop index CONCURRENTLY方式维护来保证并发效果;
建议用unique index代替unique constraints,便于后续维护;
建议对where中带多个字段and条件的高频query,参考数据分布情况,建多个字段的联合index;
建议对固定条件的(一般有特定业务含义)且选择比好(数据占比低)的query,建带where的Partial Indexes:
select * from test where status=1 and col=?; -- 其中status=1为固定的条件create index on test (col) where status=1;
- 建议对经常使用表达式作为