Index to get row count of read-only (immutable) PostgreSQL table?

后端 未结 1 1254
失恋的感觉
失恋的感觉 2021-01-24 13:52

I have a script that runs several times a day, which records the row counts of several PostgreSQL tables.

Some of the tables though are read-only and never change. (No r

相关标签:
1条回答
  • 2021-01-24 14:50

    Unfortunately, in postgresql SELECT COUNT(*) is often slower than mysql to which it often get's compared to.

    You can use the following query as an alternative to SELECT COUNT(*).

     SELECT reltuples FROM pg_class WHERE relname = 'mytable';
    

    This is not always 100% upto date but for immutable tables it will be accurate every time. And instant. For very large tables the percentage error will be very small and thus well worth the massive saving in time.

    If it does matter and the table does not contain nulls, you can use

     SELECT COUNT(primary_key_column) FROM table
    

    and this will be significantly faster than SELECT COUNT(*)

    0 讨论(0)
提交回复
热议问题