I am trying to get information about the data in my database. I have several columns in several tables that or type 'TEXT'. I want to perform a query that will create a result that looks like:
|table_name|column_name|max_length|
-----------------------------------
|my_table |name |35 |
I have the query to get all the tables and columns:
SELECT table_name, column_name FROM information_schema.columns
WHERE table_schema = 'public' AND data_type = 'text'
ORDER BY table_name
But I can't figure out how to now go through each of those tables and columns to get the max length of each column. I do have the query to get the max length of a specific column and table using:
SELECT 'my_table', 'name', MAX(LENGTH(name)) FROM my_table
How can I make a query that will get the max length dynamically based on the results of the query to get all tables and columns?
Best Answer
No need for PL/pgSQL.
You can use a variation of this solution to do everything in a single query.
Evan's comment got me thinking if there is a way to do this with a single statement per table (although I doubt that this performance optimization is really important for a "get me some information about my database query")
With a bit of XML juggling, it is indeed possible:
For the pagila demo database this returns:
The above first generates one statement per table containing one
max(length(..))
for each column.The result is then parsed and turned into rows again. It would be possible to aggregate that back into a single JSON.
To get one row per table, with the column information as a JSON value, the following can be used:
For the pagila demo database this returns: