Home / Companies / New Relic / Blog / Post Details
Content Deep Dive

How to count SQL databases quickly in PostgreSQL and MySQL

Blog post from New Relic

Post Details
Company
Date Published
Author
Kirk Haines
Word Count
2,500
Language
English
Hacker News Points
-
Summary

Counting records in database tables, particularly in MySQL and PostgreSQL, can be unexpectedly slow due to the use of Multiversion Concurrency Control, which necessitates sequential scanning of tables to determine row counts. While MyISAM in MySQL maintains a count of rows for fast retrieval, InnoDB and PostgreSQL do not, resulting in slower count operations. Techniques to speed up counting include leveraging indexes and creating triggers with functions to maintain a running count of rows, though both have trade-offs in terms of accuracy and operational overhead. For those willing to compromise on precision, estimated counts based on database metadata can be used, providing a faster but less accurate solution. Tools like New Relic offer observability solutions to monitor database performance and optimize counting strategies further.