Efficiently getting number of rows in a PostgreSQL table

Running SELECT COUNT(*) [...] on very large tables is an expensive operation because it does a full table scan. Generally an exact number isn’t needed and one’s simply looking for a rough estimate.

A very efficient way of getting a rough estimate is using the following query:

SELECT reltuples FROM pg_class WHERE relname='{{ table_name }}'

If you happen to need an exact count, you’ll have to pay the expense.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s