그곰의 생활

[PostgreSQL] 코멘트 또는 데이터 타입(사이즈)가 다른 동일 컬럼명 목록 조회 쿼리 본문

Server-side/SQL

[PostgreSQL] 코멘트 또는 데이터 타입(사이즈)가 다른 동일 컬럼명 목록 조회 쿼리

그곰 2022. 2. 9. 10:00
WITH tmp_column_dic 
  AS (
      SELECT c.column_name AS "column"
           , pgd.description AS "comment"
           , c.udt_name AS "type"
           , CASE
                  WHEN c.character_maximum_length IS NOT NULL THEN c.character_maximum_length
                  ELSE c.numeric_precision
             END AS "size"
           , c.table_name
        FROM pg_statio_all_tables st
        JOIN pg_description pgd 
          ON pgd.objoid = st.relid
        JOIN information_schema.columns c 
          ON pgd.objsubid = c.ordinal_position::integer AND c.table_schema::name = st.schemaname AND c.table_name::name = st.relname
     )
   , tmp_list 
  AS 
   ( 
    SELECT trim(split_part(k, '|&|', 1)) AS col
         , split_part(k, '|&|', 2) AS cmt
         , split_part(k, '|&|', 3) AS typ
         , split_part(k, '|&|', 4) AS sz
      FROM (
            SELECT b."column", b."comment", b."type", b."size" AS sz
                 , rpad(b.column, 60, ' ') || '|&|' || rpad(b.COMMENT, 90, ' ') || '|&|' || rpad(b.TYPE, 15, ' ') || '|&|' || lpad(COALESCE(b.SIZE, 0)::varchar, 6, '0') AS k
              FROM tmp_column_dic b
           ) x
     GROUP BY k
   )
SELECT yy."column" 
     , yy."comment"
     , yy."type"
     , yy."size"
     , array_to_string(array_agg(yy."table_name"), ',') AS table_names
  FROM (
        SELECT y.col
             , count(*) AS cnt
          FROM tmp_list y
         GROUP BY y.col
        HAVING count(*) > 1
       ) xx
  JOIN tmp_column_dic yy
    ON xx.col = yy."column"
  GROUP BY yy."column" 
         , yy."comment"
         , yy."type"
         , yy."size"
Comments