Skip to content

Instantly share code, notes, and snippets.

@alexanderlz
Last active February 1, 2023 14:38
Show Gist options
  • Save alexanderlz/7302623 to your computer and use it in GitHub Desktop.
Save alexanderlz/7302623 to your computer and use it in GitHub Desktop.
Get column description in postgresql/redshift
SELECT description FROM pg_catalog.pg_description WHERE objsubid =
(
SELECT ordinal_position FROM information_schema.columns WHERE table_name='YOUR_TABLE_NAME' AND column_name='YOUR_COLUMN_NAME'
)
and objoid =
(
SELECT oid FROM pg_class WHERE relname = 'YOUR_TABLE_NAME' AND relnamespace =
(
SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = 'public'
)
);
@daviibf
Copy link

daviibf commented Feb 1, 2023

This thread helped me a lot too. Studying a little the query from @johnson-jay-l , I was able to add the table owner as well:

WITH tables AS (
    SELECT c.oid,
           ns.nspname as schema_name,
           c.relname as table_name,
           d.description as table_description,
           pg_get_userbyid(c.relowner) AS table_owner
    FROM pg_catalog.pg_class AS c
    JOIN pg_catalog.pg_namespace AS ns
      ON c.relnamespace = ns.oid
    LEFT JOIN pg_catalog.pg_description d
      on c.oid = d.objoid
     and d.objsubid = 0
     WHERE ns.nspname not in ('pg_catalog') 
)
SELECT t.oid,
       c.table_schema as schema_name,
       c.table_name AS table_name,
       t.table_description,
       c.column_name AS column_name,
       c.ordinal_position,
       d.description as column_description,
       t.table_owner
from tables t
join information_schema.columns c
    on c.table_schema = t.schema_name
   and c.table_name = t.table_name
left join pg_catalog.pg_description d
   ON d.objoid = t.oid
  AND d.objsubid = c.ordinal_position
  AND d.objsubid > 0
where 1=1
order by
    t.schema_name,
    t.table_name,
    c.ordinal_position

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment