テーブル定義を確認するにはpsqlの\dコマンドを使う。SQLで取得する場合はinformation_schema.columnsを参照する。

psqlでテーブル定義を確認する

psqlで\d テーブル名を実行すると、カラム名、データ型、NOT NULL制約、デフォルト値が表示される。主キーとインデックスも併せて確認できる。

testdb=# \d users
                           Table "public.users"
   Column   |            Type             | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+---------
 id         | integer                     |           | not null |
 name       | text                        |           | not null |
 email      | character varying(255)      |           |          |
 address    | text                        |           |          |
 created_at | timestamp without time zone |           |          | now()
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
    "idx_users_email" btree (email)

インデックスの詳細を確認する方法は以下を参照。
» 【PostgreSQL】指定したテーブルのインデックスを確認する

コメントも確認する

\d+を使うとカラムのコメントがDescription列に表示される。

testdb=# \d+ users
                                                        Table "public.users"
   Column   |            Type             | Collation | Nullable | Default | Storage  | Compression | Stats target |  Description
------------+-----------------------------+-----------+----------+---------+----------+-------------+--------------+----------------
 id         | integer                     |           | not null |         | plain    |             |              |
 name       | text                        |           | not null |         | extended |             |              |
 email      | character varying(255)      |           |          |         | extended |             |              | メールアドレス
 address    | text                        |           |          |         | extended |             |              |
 created_at | timestamp without time zone |           |          | now()   | plain    |             |              |
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
    "idx_users_email" btree (email)
Access method: heap

SQLでカラム一覧を取得する

information_schema.columnsにカラム情報が格納されている。psqlを使えない場合や、アプリケーションから取得する場合に使う。

select column_name, data_type, is_nullable, column_default
  from information_schema.columns
  where table_name = 'users'
  order by ordinal_position;
 column_name |          data_type          | is_nullable | column_default
-------------+-----------------------------+-------------+----------------
 id          | integer                     | NO          |
 name        | text                        | NO          |
 email       | character varying           | YES         |
 address     | text                        | YES         |
 created_at  | timestamp without time zone | YES         | now()
(5 rows)

テーブル一覧と併せて取得する方法は以下を参照。
» 【PostgreSQL】SQLでテーブル一覧を取得する

データ型の桁数を取得する

data_typeには桁数が含まれない。\dではcharacter varying(255)と表示されるカラムも、data_typeではcharacter varyingとなる。

桁数はcharacter_maximum_lengthで取得する。

select column_name, data_type, character_maximum_length, is_nullable
  from information_schema.columns
  where table_name = 'users'
  order by ordinal_position;
 column_name |          data_type          | character_maximum_length | is_nullable
-------------+-----------------------------+--------------------------+-------------
 id          | integer                     |                          | NO
 name        | text                        |                          | NO
 email       | character varying           |                      255 | YES
 address     | text                        |                          | YES
 created_at  | timestamp without time zone |                          | YES
(5 rows)

桁数とコメントをまとめて取得する

pg_attributeを参照すると、\d+と同じ形式の情報をSQLで取得できる。format_typeは桁数を含むデータ型を返し、col_descriptionはカラムのコメントを返す。

select a.attname as column_name,
       format_type(a.atttypid, a.atttypmod) as data_type,
       a.attnotnull as not_null,
       col_description(a.attrelid, a.attnum) as comment
  from pg_attribute a
  where a.attrelid = 'users'::regclass
    and a.attnum > 0
    and not a.attisdropped
  order by a.attnum;
 column_name |          data_type          | not_null |    comment
-------------+-----------------------------+----------+----------------
 id          | integer                     | t        |
 name        | text                        | t        |
 email       | character varying(255)      | f        | メールアドレス
 address     | text                        | f        |
 created_at  | timestamp without time zone | f        |
(5 rows)

attnum > 0はシステムカラムを除外する条件、not attisdroppedは削除済みのカラムを除外する条件である。

information_schema.columnsのカラム

information_schema.columnsはカラム数が多いため、上記の例では一部に絞って取得している。PostgreSQL 16では43個のカラムが存在する。

よく使うカラムは次のとおり。

カラム内容
table_schemaテーブルが属するスキーマ名
table_nameテーブル名
column_nameカラム名
ordinal_positionカラムの定義順
column_defaultデフォルト値
is_nullableNULLを許可するか(YESまたはNO)
data_typeデータ型。桁数は含まない
character_maximum_length文字列型の最大長
numeric_precision数値型の精度
numeric_scale数値型の位取り
is_identityIDENTITY列か
is_generated生成列か

上記以外には次のカラムが存在する。

  • table_catalog
  • character_octet_length
  • numeric_precision_radix
  • datetime_precision
  • interval_typeinterval_precision
  • character_set_catalogcharacter_set_schemacharacter_set_name
  • collation_catalogcollation_schemacollation_name
  • domain_catalogdomain_schemadomain_name
  • udt_catalogudt_schemaudt_name
  • scope_catalogscope_schemascope_name
  • maximum_cardinality
  • dtd_identifier
  • is_self_referencing
  • identity_generationidentity_startidentity_incrementidentity_maximumidentity_minimumidentity_cycle
  • generation_expression
  • is_updatable

MySQLでの確認方法は以下も参照。
参考: 【MySQL】テーブル定義とカラム一覧を確認する