テーブルのカラム属性一覧取得 (mysql,postgresql)


テーブルのカラム属性一覧を取得するSQLです。
<テーブル名>の部分を実際の物理テーブル名にして実行します。

my_sqlの場合

select c.table_name,c.column_name , c.is_nullable, column_type
from information_schema.columns c
where table_name='<テーブル名>' order by ordinal_position
 

postgresqlの場合

SELECT  relname,attname,typname,case typname
                when 'timestamp' then 14
                when 'numeric' then (atttypmod - 4) / 65536
                else atttypmod-4
                end as len
                ,case attnotnull
                when 't' then 'not null'
                else '' end as attnotnull
          FROM    pg_class,pg_attribute,pg_type
          WHERE   relkind     ='r'
          AND relname     ='<テーブル名>'
          AND pg_class.oid = pg_attribute.attrelid
          AND attnum      > 0
          AND pg_type.oid = atttypid
          order by attnum
カテゴリー: データベース
カテゴリー