How to delete many rows from frequently accessed table

喜欢而已 提交于 2019-12-01 17:56:46
  1. Indexes are completely useless for operations on 90% of all rows. Sequential scans will be faster either way.

  2. If you need to allow concurrent reads, you cannot take an exclusive lock on the table. So you can also not drop any indexes in the same transaction.

  3. You could drop indexes in separate transactions to keep the duration of the exclusive lock at a minimum. And later use CREATE INDEX CONCURRENTLY to rebuild the index in the background - and only take a very brief exclusive lock.

If you have a stable condition to identify the 10 % of rows that stay, I would strongly suggest a partial index on just those rows to get the best for both:

  • Reading queries can access the table quickly (using the partial index) at all times.
  • The big DELETE is not going to modify the partial index at all, since none of the rows are involved in the DELETE.

CREATE INDEX foo (some_id) WHERE delete_flag = FALSE;

Assuming delete_flag is boolean. You have to include the same predicate in your queries (even if it seems logically redundant) to make sure Postgres understands it can use the partial index.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!