PostgreSQL – How to Show Number of Tables for Each Database

postgresqlselecttable

Related to my previous question, I use the code below to get all databases:

SELECT datname
FROM pg_database
WHERE NOT datistemplate
  AND datallowconn
  AND datname <> 'postgres';

How to get the number of tables from each database returned from the command above?

There is no master database in Postgres like Microsoft SQL Server, where I could do a query for all the databases.

Is it possible in Postgres?

Thank you

Best Answer

You can use something like the following which will list every table (with their row counts) for every schema in the database:

select n.nspname as table_schema,
       c.relname as table_name,
       c.reltuples as rows
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where c.relkind = 'r'
      and n.nspname not in ('information_schema','pg_catalog')
order by c.reltuples desc;

I believe you'll need to use dynamic SQL in order to run it in every database. Here's a walkthrough.