How do I speed up counting rows in a PostgreSQL table?

前端 未结 6 924
悲哀的现实
悲哀的现实 2020-12-02 18:37

We need to count the number of rows in a PostgreSQL table. In our case, no conditions need to be met, and it would be perfectly acceptable to get a row estimate if that sig

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 19:24

    Aside from running COUNT() on an indexed field (which hopefully 'id' is) - the next best thing would be to actually cache the row count in some table using a trigger on INSERT. Naturally, you'll be checking the cache instead.

    For an approximation you can try this (from https://wiki.postgresql.org/wiki/Count_estimate):

    select reltuples from pg_class where relname='tablename';
    

提交回复
热议问题