2015年1月20日 : してログ

テーブルの定義(データ型、フィールド長、カラムの定義順、デフォルト値、NOT NULLなど)を一括して取得する SQL 文です。 テーブル名は、relname = 'table_name' の部分で指定します。 前の記事の方法より、こちらのほうが簡単で他の情報も取得できます。

select
	*
from
	information_schema.columns
where
	table_catalog = current_database()
		and
	table_name = 'table_name'
order by
	ordinal_position
;

テーブルを構成する、各フィールドのデータ型を取得するSQL文は、下記のようなります。 テーブル名は、relname = 'table_name' の部分で指定します。 プログラム内でこれらを取得することで、入力値の桁数や、データ型のチェックに役立ちます。

select
	at.attname,
	format_type(at.atttypid, at.atttypmod)
from
	pg_attribute as at
		left join pg_type as tp on (at.atttypid = tp.oid)
where
	at.attnum > 0 and
	at.attrelid = (select relfilenode from pg_class where relname = 'table_name')
order by
	at.attnum
;