11

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
... 
4
  • the number of rows in that table... Commented Feb 23, 2015 at 6:22
  • 1
    Please look here: row count in postgres and sysobjects in postgres Commented Feb 23, 2015 at 6:36
  • Thanks @Hockenberry - strange that it didn't show up in search for me! I'd close this question, but it has an answer Commented Feb 23, 2015 at 6:50
  • I am using this tool which has its own command for this Commented Feb 23, 2015 at 7:30

2 Answers 2

17

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(*)

Sign up to request clarification or add additional context in comments.

2 Comments

Why a LEFT JOIN when you make it an INNER JOIN?
Note that you might have to run the ANALYZE command on your db before this gives correct results. For me there was a disparity between SELECT count(*) FROM table; and the results this query gave me for the table. Until I ran ANALYZE.
5

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

1 Comment

One caveat to this (from the documentation): "This is only an estimate used by the planner."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.