My goal is to generate a report showing the number of records saved each day/month in a PostgreSQL database under a specific schema.
So far i have something simiilar byt with size (MB) not count and with overal sum
SELECT
table_schema || '.' || table_name AS table_full_name,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) AS size
FROM information_schema.tables
where table_schema = 'public'
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC;
Is there any solution to generate such report:
TABLE NAME | count | data |
---|---|---|
foo | 312 | 30-03-2023 |
foo | 111 | 29-03-2023 |
bar | 312 | 30-03-2023 |
bar | 344 | 29-03-2023 |
2
Answers
If you can afford to get approximate counts (maintained by stuff like
vacuum analyze
statements), then you could use such a query:then create a table once and insert first batch:
Then in a cron or something, to append new data:
Then, the final query to display results:
Otherwise, you will need to use dynamic queries, using plpgsql stuff like:
return query execute
: https://www.postgresql.org/docs/15/plpgsql-control-structures.html#id-1.8.8.8.3.4execute format('…')
as exemplified in https://www.postgresql.org/docs/15/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATINGTake a look at
pg_stat_all_tables
system view:You can take snapshots of this view daily using
cron
orpg_cron
to monitor not only the estimated number of rows but also traffic leading to that number.To see all that traffic live, you can tap into the logical streaming replication protocol using
pg_recvlogical
.