mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Get A Quick Approximate Count Of A Table as a Postgres til
This commit is contained in:
@@ -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)
|
||||
|
||||
42
postgres/get-a-quick-approximate-count-of-a-table.md
Normal file
42
postgres/get-a-quick-approximate-count-of-a-table.md
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user