Skip to Main Content
PostgreSQL 9 Administration Cookbook - Second Edition
book

PostgreSQL 9 Administration Cookbook - Second Edition

by Simon Riggs, GIANNI CIOLLI, Hannu Krosing, Gabriele Bartolini
April 2015
Intermediate to advanced content levelIntermediate to advanced
504 pages
11h 41m
English
Packt Publishing
Content preview from PostgreSQL 9 Administration Cookbook - Second Edition

Quickly estimating the number of rows in a table

We don't always need an accurate count of rows, especially on a large table—that may take a long time to execute. Administrators often need to estimate how big a table is so that they can estimate how long other operations may take.

How to do it…

We can get a quick estimate of the number of rows in a table using roughly the same calculation that the Postgres optimizer uses:

SELECT (CASE WHEN reltuples > 0 THEN pg_relation_size('mytable')*reltuples/(8192*relpages) ELSE 0 END)::bigint AS estimated_row_count FROM pg_class WHERE oid = 'mytable'::regclass;

This gives us the following output:

estimated_count
─────────────────
             293
(1 row)

It returns a row count very quickly, no matter how large the table ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PostgreSQL 10 Administration Cookbook - Fourth Edition

PostgreSQL 10 Administration Cookbook - Fourth Edition

Simon Riggs, Gianni Ciolli
Mastering PostgreSQL 10

Mastering PostgreSQL 10

Hans-Jürgen Schönig

Publisher Resources

ISBN: 9781849519069Supplemental Content