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

前端 未结 6 930
悲哀的现实
悲哀的现实 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:01

    Count is slow for big tables, so you can get a close estimate this way:

    SELECT reltuples::bigint AS estimate 
    FROM pg_class 
    WHERE relname='tableName';
    

    and its extremely fast, results are not float, but still a close estimate.

    • reltuples is a column from pg_class table, it holds data about "number of rows in the table. This is only an estimate used by the planner. It is updated by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX" (manual)
    • The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, composite types, and some kinds of special relation (manual)
    • "Why is "SELECT count(*) FROM bigtable;" slow?" : http://wiki.postgresql.org/wiki/FAQ#Why_is_.22SELECT_count.28.2A.29_FROM_bigtable.3B.22_slow.3F

提交回复
热议问题