简体   繁体   中英

How to get the sum of FreeSpace of all the tables in a database

To Get all the user Table names in the database using:

select relname from pg_stat_user_tables;

relname
-------
Table1
Table2
Table3

To Get the free space marked by vacuum of one table using:

SELECT sum(avail) FROM pg_freespace('Table1');

sum
-----
1728

I want to get the total free space of all the tables in single query.

Say for example,

Table1 has 1728 freespace
Table2 has 100 freespace
Table3 has 100 freespace

How to get 1928 as answer with a query?

I suggest you can query it first through a table list all table in database such as pg_table and then sum it all. Such like 2 query below: 1. list all table and its freespace:

SELECT fulltablename, sum(avail) as freespace
FROM (
    SELECT concat(schemaname,'.',tablename) as fulltablename, (pg_freespace(concat(schemaname,'.',tablename))).* 
      FROM pg_tables 
    ) t
GROUP BY fulltablename
  1. sum all freespace in database:
SELECT sum(avail) as freespace
FROM (
    SELECT concat(schemaname,'.',tablename) as fulltablename, (pg_freespace(concat(schemaname,'.',tablename))).* 
      FROM pg_tables 
    ) t

I hope this answer will satisfy you.

I used the below query to solve my problem (To get the sum of freespace of all table of my schema)

SELECT sum(avail) as freespace
FROM (
    SELECT  (pg_freespace(concat(schemaname,'."',tablename,'"'))).* 
    FROM pg_tables where schemaname = 'mySchema'
) t
;

I have tweaked Mabu's sql to give a single total freespace value for all tables

SELECT sum(freespace) as TotalFreeSpace
FROM (
    SELECT fulltablename, sum(avail) as freespace
    FROM (
        SELECT concat(schemaname,'.',tablename) as fulltablename, 
        (pg_freespace(concat(schemaname,'.',tablename))).*
        FROM pg_tables
        ) t
    GROUP BY fulltablename) f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM