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

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

    For a quick estimate:

    SELECT reltuples FROM pg_class WHERE oid = 'my_schema.my_table'::regclass;
    

    This is superior to the queries presented so far - including the advice in the Postgres Wiki on slow counting. (Updated that by now.):
    relname is not unique in pg_class. There can be multiple tables with the same relname in multiple schemas of the database. That's regularly the case in my installations.

    And a query on pg_stat_user_tables is many times slower, as that's a view on a couple of tables.

    If you do not schema-qualify the table name, a cast to regclass observes the current search_path to pick the best match. And if the table does not exist (or cannot be seen) in any of the schemas in the search_path you get an error message.

    Details on Object Identifier Types in the manual.

    Related answer with new options:

    • Fast way to discover the row count of a table in PostgreSQL

提交回复
热议问题