information_schemaビューを使ってテーブル情報を取得する
PostgreSQLにおける「DESCRIBE TABLE」コマンドの解説
PostgreSQLには、テーブルの構造や属性情報を表示する「DESCRIBE TABLE」コマンドは存在しません。しかし、いくつかの代替方法を用いて、同様の情報を得ることができます。
代替方法
-
psqlコマンドの
\d
オプションを使用することで、テーブルの構造情報を表示できます。例:
\d テーブル名
出力例:
Name | Type | Modifier | Description ------- | -------- | -------- | -------- id | integer | not null | name | text | | created_at | timestamp without time zone | |
-
information_schema.columns
ビューをクエリすることで、テーブルの各列に関する詳細情報を取得できます。SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_name = 'テーブル名';
column_name | data_type | is_nullable | column_default ------------- | -------- | -------- | -------- id | integer | NO | name | text | YES | created_at | timestamp without time zone | YES |
補足
-
\d+ テーブル名
\d テーブル名
\d customers
Name | Type | Modifier | Description
------- | -------- | -------- | --------
id | integer | not null |
name | text | |
email | text | |
created_at | timestamp without time zone | |
information_schemaビュー
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'テーブル名';
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'customers';
column_name | data_type | is_nullable | column_default
------------- | -------- | -------- | --------
id | integer | NO |
name | text | YES |
email | text | YES |
created_at | timestamp without time zone | YES |
pgAdmin
- pgAdminでデータベースに接続します。
- テーブル名を右クリックします。
- メニューから「構造を表示」を選択します。
- 上記のサンプルコードは、PostgreSQL 14.2で動作確認しています。
- テーブル名や列名は適宜変更してください。
PostgreSQLのテーブル構造を表示するその他の方法
\dd
コマンドは、テーブルの定義と制約を表示します。
\dd テーブル名
-- テーブル: public.customers
-- 列:
CREATE TABLE public.customers (
id integer NOT NULL DEFAULT nextval('customers_id_seq'::regclass),
name text,
email text,
created_at timestamp without time zone
);
-- 制約:
ALTER TABLE ONLY public.customers
ADD CONSTRAINT customers_pkey PRIMARY KEY (id);
psqlの \x コマンド
\x テーブル名
id | name | email | created_at
------- | -------- | -------- | --------
1 | 山田太郎 | [email protected] | 2023-11-14 10:29:00
2 | 佐藤花子 | [email protected] | 2023-11-15 11:30:00
外部ツール
pgAdminのようなGUIツールや、DBeaverのようなデータベース管理ツールを使用すれば、テーブル構造を視覚的に確認できます。
- 上記の方法以外にも、PostgreSQLのテーブル構造を表示する方法はいくつかあります。
database postgresql command