Placing query output into psql variables
It is also possible to store some values produced by a query into variables, for instance to reuse them later in other queries.
In this recipe we demonstrate this approach with a concrete example.
Getting ready
In recipe Controlling automatic database maintenance of Chapter 9, Regular Maintenance, we describe VACUUM
, showing that it runs regularly on each table based on the number of rows that might need vacuuming ("dead rows"). VACUUM will run if that number exceeds a given threshold, which by default is just above 20% of the row count.
In this recipe we create a script that picks the table with the largest number of dead rows, and runs VACUUM on it.
How to do it…
The script is as follows:
SELECT schemaname , relname , n_dead_tup , n_live_tup FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 1 \gset \qecho Running VACUUM on table :"relname" in schema :"schemaname" \qecho Rows before: :n_dead_tup dead, :n_live_tup live VACUUM ANALYZE :schemaname.:relname...