How do you find the row count for all your tables in Postgres

前端 未结 15 2239
无人及你
无人及你 2020-11-22 12:31

I\'m looking for a way to find the row count for all my tables in Postgres. I know I can do this one table at a time with:

SELECT count(*) FROM table_name;
         


        
15条回答
  •  醉梦人生
    2020-11-22 12:59

    Simple Two Steps:
    (Note : No need to change anything - just copy paste)
    1. create function

    create function 
    cnt_rows(schema text, tablename text) returns integer
    as
    $body$
    declare
      result integer;
      query varchar;
    begin
      query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
      execute query into result;
      return result;
    end;
    $body$
    language plpgsql;
    

    2. Run this query to get rows count for all the tables

    select sum(cnt_rows) as total_no_of_rows from (select 
      cnt_rows(table_schema, table_name)
    from information_schema.tables
    where 
      table_schema not in ('pg_catalog', 'information_schema') 
      and table_type='BASE TABLE') as subq;
    

    or

    To get rows counts tablewise

    select
      table_schema,
      table_name, 
      cnt_rows(table_schema, table_name)
    from information_schema.tables
    where 
      table_schema not in ('pg_catalog', 'information_schema') 
      and table_type='BASE TABLE'
    order by 3 desc;
    

提交回复
热议问题