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

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

    You can ask for the exact value of the count in the table by simply using trigger AFTER INSERT OR DELETE Something like this

    CREATE TABLE  tcounter(id serial primary key,table_schema text, table_name text, count serial);
    
    insert into tcounter(table_schema, table_name,count) select 'my_schema', 'my_table', count(*) from my_schema.my_table;
    

    and use trigger

    CREATE OR REPLACE FUNCTION ex_count()
    RETURNS trigger AS
    $BODY$
    BEGIN
        IF (TG_OP='INSERT') THEN
          UPDATE tcounter set count = count + 1 where table_schema = TG_TABLE_SCHEMA::TEXT and table_name = TG_TABLE_NAME::TEXT;
        ELSIF  (TG_OP='DELETE') THEN
          UPDATE tcounter set count = count - 1 where table_schema = TG_TABLE_SCHEMA::TEXT and table_name = TG_TABLE_NAME::TEXT;
        END IF;
    RETURN NEW;
    END$BODY$
    LANGUAGE plpgsql VOLATILE
    COST 100;
    
    CREATE TRIGGER tg_counter  AFTER INSERT OR DELETE
      ON my_schema.my_table  FOR EACH ROW  EXECUTE PROCEDURE ex_count();
    

    And ask for count

    select * from tcounter where table_schema =  'my_schema' and table_name = 'my_table'
    

    it means you select count(*) once for initialize first record

提交回复
热议问题