Generally, if you don't need an exact count, there is a much faster way:
SELECT reltuples::bigint AS estimate
FROM pg_class
WHERE oid = 'image'::regclass;
See:
As a matter of factStrictly speaking, in a DB with concurrent write access every count is an estimate, because the number may be outdated the instant you get it.
But, like @a_horse commented, there is something off in your DB. Counting a million rows should not take more than a few seconds in the worst case. (Much less with modern Postgres on modern hardware.)
That your app will never delete images from this table
"app will never delete images from this table" makes this even more suspicious, because there shouldn't be many dead rows then. (Or are you updating a lot?) A huge amount of dead tuples could slow you down - and call for VACUUM
. Normally, autovacuumautovacuum
takes care of this. Did you enable it? (It's theIt's on by default in modern Postgres.)
Check for dead tuples: