What is the most efficient way to get a row count of all tables in my database?
I'm using a Postgres database.
Example Result
table_name row_count
------------ -------------
some_table 1,234
foobar 5,678
another_table 32
...
Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).
The information schema is a built-in schema that's common to every PostgreSQL database. You can run SQL queries against tables in the information_schema to fetch schema metadata for a database.
reltuples ... Number of rows in the table. This is only an estimate used by the planner. It is updated by VACUUM , ANALYZE , and a few DDL commands such as CREATE INDEX .
if you want a perticular table's rowcount then it will work
SELECT reltuples FROM pg_class WHERE oid = 'my_schema.my_table'::regclass;
reltuples is a column from pg_class table, it holds data about "number of rows >in the table. This is only an estimate used by the planner.
and if your want a list of all tables with its rowcount then it will do the job
SELECT
pgClass.relname AS tableName,
pgClass.reltuples AS rowCount
FROM
pg_class pgClass
INNER JOIN
pg_namespace pgNamespace ON (pgNamespace.oid = pgClass.relnamespace)
WHERE
pgNamespace.nspname NOT IN ('pg_catalog', 'information_schema') AND
pgClass.relkind='r'
"Why is "SELECT count(*) FROM bigtable;" slow?" : count(*)
For total row count of entire database use this
SELECT
SUM(pgClass.reltuples) AS totalRowCount
FROM
pg_class pgClass
LEFT JOIN
pg_namespace pgNamespace ON (pgNamespace.oid = pgClass.relnamespace)
WHERE
pgNamespace.nspname NOT IN ('pg_catalog', 'information_schema') AND
pgClass.relkind='r'
And the row counts for the specific tables in the same database go for this
SELECT
pgClass.relname AS tableName,
pgClass.reltuples AS rowCount
FROM
pg_class pgClass
LEFT JOIN
pg_namespace pgNamespace ON (pgNamespace.oid = pgClass.relnamespace)
WHERE
pgNamespace.nspname NOT IN ('pg_catalog', 'information_schema') AND
pgClass.relkind='r'
For reference here is the link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With