It can be very slow to count a large data set. I tried different ways to optimize the counting performance, but a lot of them introduced much complexity.
I found we could significantly improve the counting performance by removing redundant table joins and/or replacing inner joins with left outer joins.
With this approach, the query times reduced from dozens of seconds to milliseconds on a PostgreSQL 9.2 server: https://i.imgur.com/f3v4E4J.png
Versions of PostgreSQL prior to 9.2 don't support for index-only scans. So if we use a PostgreSQL 8.4 server, the performance improvement will not be so obvious: https://i.imgur.com/HNkNypM.png
It can be very slow to count a large data set. I tried different ways to optimize the counting performance, but a lot of them introduced much complexity.
I found we could significantly improve the counting performance by removing redundant table joins and/or replacing
inner joins withleft outer joins.With this approach, the query times reduced from dozens of seconds to milliseconds on a PostgreSQL 9.2 server: https://i.imgur.com/f3v4E4J.png
Versions of PostgreSQL prior to 9.2 don't support for index-only scans. So if we use a PostgreSQL 8.4 server, the performance improvement will not be so obvious: https://i.imgur.com/HNkNypM.png