list table sizes for all tables in a postgresql database

Viewed 1267

I can get the number of columns in all the tables in a postgresql database by

SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
GROUP BY TABLE_SCHEMA, TABLE_NAME;

I can get the number of rows in a specific table in a database by

SELECT  COUNT(*) FROM mytable

How to obtain column and row counts for all table in a database in one query?

2 Answers

Combine your query using a CTE and join it with the one posted on this answer, as @a_horse_with_no_name suggested, e.g.

WITH j AS (
  SELECT table_schema, table_name, count(*) AS count_columns
  FROM information_schema.columns
  GROUP BY table_schema, table_name
) 
SELECT 
  nspname AS schemaname,relname,reltuples,count_columns
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
JOIN j ON j.table_name = relname AND j.table_schema = nspname 
WHERE 
  nspname NOT IN ('pg_catalog', 'information_schema') AND
  relkind='r' 
ORDER BY reltuples DESC;
Related