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

前端 未结 15 2065
无人及你
无人及你 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:09

    Here is a much simpler way.

    tables="$(echo '\dt' | psql -U "${PGUSER}" | tail -n +4 | head -n-2 | tr -d ' ' | cut -d '|' -f2)"
    for table in $tables; do
    printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"
    done
    

    output should look like this

    auth_group: 0
    auth_group_permissions: 0
    auth_permission: 36
    auth_user: 2
    auth_user_groups: 0
    auth_user_user_permissions: 0
    authtoken_token: 2
    django_admin_log: 0
    django_content_type: 9
    django_migrations: 22
    django_session: 0
    mydata_table1: 9011
    mydata_table2: 3499
    

    you can update the psql -U "${PGUSER}" portion as needed to access your database

    note that the head -n-2 syntax may not work in macOS, you could probably just use a different implementation there

    Tested on psql (PostgreSQL) 11.2 under CentOS 7


    if you want it sorted by table, then just wrap it with sort

    for table in $tables; do
    printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"
    done | sort -k 2,2nr
    

    output;

    mydata_table1: 9011
    mydata_table2: 3499
    auth_permission: 36
    django_migrations: 22
    django_content_type: 9
    authtoken_token: 2
    auth_user: 2
    auth_group: 0
    auth_group_permissions: 0
    auth_user_groups: 0
    auth_user_user_permissions: 0
    django_admin_log: 0
    django_session: 0
    

提交回复
热议问题