From e9ca21dbbb76a9e20c17f9ac192d254319f9e4c8 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 17 Sep 2021 14:40:24 -0500 Subject: [PATCH] Add Get A Quick Approximate Count Of A Table as a Postgres til --- README.md | 3 +- ...et-a-quick-approximate-count-of-a-table.md | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 postgres/get-a-quick-approximate-count-of-a-table.md diff --git a/README.md b/README.md index c83cd92..1038c5d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1151 TILs and counting..._ +_1152 TILs and counting..._ --- @@ -572,6 +572,7 @@ _1151 TILs and counting..._ - [Generate Random UUIDs Without An Extension](postgres/generate-random-uuids-without-an-extension.md) - [Generate Series Of Numbers](postgres/generate-series-of-numbers.md) - [Generating UUIDs With pgcrypto](postgres/generating-uuids-with-pgcrypto.md) +- [Get A Quick Approximate Count Of A Table](postgres/get-a-quick-approximate-count-of-a-table.md) - [Get The Size Of A Database](postgres/get-the-size-of-a-database.md) - [Get The Size Of A Table](postgres/get-the-size-of-a-table.md) - [Get The Size Of An Index](postgres/get-the-size-of-an-index.md) diff --git a/postgres/get-a-quick-approximate-count-of-a-table.md b/postgres/get-a-quick-approximate-count-of-a-table.md new file mode 100644 index 0000000..1022d33 --- /dev/null +++ b/postgres/get-a-quick-approximate-count-of-a-table.md @@ -0,0 +1,42 @@ +# Get A Quick Approximate Count Of A Table + +Really large PostgreSQL tables can be slow to work with. Even a count of the +rows in a really large table can take a while to tabulate. I'm talking about +tables on the order of hundreds of millions of rows. + +For instance, here is a query grabbing the count of a ~400 million row table. + +```sql +> select count(*) from events; + + count +----------- + 427462316 +(1 row) + +Time: 55113.794 ms +``` + +If I'm willing to wait nearly a minute (55 seconds), I can get an accurate +count of the rows in this `events` table. + +If I don't want to wait and an approximate count will do, there are faster +ways. One way is to query the `pg_class` table. + +``` +> select reltuples::numeric as count + from pg_class + where relname='events'; + + count +----------- + 427462000 +(1 row) + +Time: 0.413 ms +``` + +The resulting count is within hundreds of the actual value and tells me what I +need to know. And instead of 55 seconds, it takes less than half a millisecond. + +[source](https://andyatkinson.com/postgresql-tips)