I am able to fetch a table of names and their columns with the query below:
SELECT t.table_name, array_agg(c.column_name::text) as columns
FROM information_schema.tables t inner
JOIN information_schema.columns c on t.table_name = c.table_name
WHERE t.table_schema = 'public'
AND t.table_type= 'BASE TABLE'
AND c.table_schema = 'public' group by t.table_name;
However, I want it to return the columns in order of ordinal position. How do I edit this query to do so?
I've tried adding ORDER BY ordinal_position but am unsure where to place it.
One way: add a per-aggregate
ORDER BY:Alternatively, order rows in a subquery. See:
While being at it, here's an alternative, basically equivalent query based on Postgres catalog tables:
There are pros and cons. For details, see: