【SQL】Postgresql テーブル・カラムの一覧表をSQLで取得する

テーブルとカラムと桁・型をリストアップするためのSQLです。
抽出した結果を活用して、ExcelやDBファンクション等を使ってデータ作りやチェック用のSQLを作ったり等、
そんな時に使えるかと思います。よく調べては書くことが多いので、備忘録として記載します。
桁の判定は若干微妙です。他に良い方法があるのかもしれないですが。。(^^;)

select
    tbl.oid as table_oid,
    tbl.relname as table_name, --テーブル名
    col.attnum, --項番
    col.attname as column_name, --カラム名
    upper(typ.typname) as column_datatype, --カラムデータ型
    case when exists (select 1 from information_schema.table_constraints tcs
    inner join information_schema.constraint_column_usage ccu on
      ccu.table_catalog = tcs.table_catalog  and
      ccu.table_schema = tcs.table_schema and
      ccu.table_name = tcs.table_name and ccu.constraint_name = tcs.constraint_name
     where tcs.constraint_type = 'PRIMARY KEY' and tcs.table_catalog = 'postgres' /*データベース名*/
      and tcs.table_name = tbl.relname and ccu.column_name = col.attname
    ) then '○' end as primary_key, --プライマリーキー
    nullif(((case when typ.typname in ('date','timestamp','time','bytea','text') then 0 else (col.atttypmod - 4) end)
    / (case when typ.typname in ('numeric','decimal') then 65536 else 1 end)),0) as column_length, --桁
    case when col.attnotnull then 'NOT NULL' end as notnull, --NOTNULL
    case when col.atthasdef then 'DEFAULT ' || def.adsrc end as default --デフォルト値
from
    pg_class tbl
inner join pg_attribute col on col.attrelid = tbl.oid and col.attnum >= 0 and col.attisdropped <> true
inner join pg_type typ on typ.oid = col.atttypid and typ.typisdefined
left join pg_attrdef def on def.adrelid = tbl.oid and def.adnum = col.attnum
where
    tbl.relkind = 'r'
/*オーナーユーザー名で絞込む場合はコメントを外す*/
--and exists (select 1 from pg_user usr where usr.usesysid = tbl.relowner and usr.usename = 'user123')
/*システムテーブルを除く*/
and tbl.relname not like 'pg_%'
and tbl.relname not like 'sql_%'
order by tbl.relname, col.attnum
タイトルとURLをコピーしました