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

前端 未结 15 2240
无人及你
无人及你 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 13:21

    The hacky, practical answer for people trying to evaluate which Heroku plan they need and can't wait for heroku's slow row counter to refresh:

    Basically you want to run \dt in psql, copy the results to your favorite text editor (it will look like this:

     public | auth_group                     | table | axrsosvelhutvw
     public | auth_group_permissions         | table | axrsosvelhutvw
     public | auth_permission                | table | axrsosvelhutvw
     public | auth_user                      | table | axrsosvelhutvw
     public | auth_user_groups               | table | axrsosvelhutvw
     public | auth_user_user_permissions     | table | axrsosvelhutvw
     public | background_task                | table | axrsosvelhutvw
     public | django_admin_log               | table | axrsosvelhutvw
     public | django_content_type            | table | axrsosvelhutvw
     public | django_migrations              | table | axrsosvelhutvw
     public | django_session                 | table | axrsosvelhutvw
     public | exercises_assignment           | table | axrsosvelhutvw
    

    ), then run a regex search and replace like this:

    ^[^|]*\|\s+([^|]*?)\s+\| table \|.*$
    

    to:

    select '\1', count(*) from \1 union/g
    

    which will yield you something very similar to this:

    select 'auth_group', count(*) from auth_group union
    select 'auth_group_permissions', count(*) from auth_group_permissions union
    select 'auth_permission', count(*) from auth_permission union
    select 'auth_user', count(*) from auth_user union
    select 'auth_user_groups', count(*) from auth_user_groups union
    select 'auth_user_user_permissions', count(*) from auth_user_user_permissions union
    select 'background_task', count(*) from background_task union
    select 'django_admin_log', count(*) from django_admin_log union
    select 'django_content_type', count(*) from django_content_type union
    select 'django_migrations', count(*) from django_migrations union
    select 'django_session', count(*) from django_session
    ;
    

    (You'll need to remove the last union and add the semicolon at the end manually)

    Run it in psql and you're done.

                ?column?            | count
    --------------------------------+-------
     auth_group_permissions         |     0
     auth_user_user_permissions     |     0
     django_session                 |  1306
     django_content_type            |    17
     auth_user_groups               |   162
     django_admin_log               |  9106
     django_migrations              |    19
    [..]
    

提交回复
热议问题