バージョンごとのドキュメント一覧

5.6. テーブルの変更 #

<title>Modifying Tables</title>

When you create a table and you realize that you made a mistake, or the requirements of the application change, you can drop the table and create it again. But this is not a convenient option if the table is already filled with data, or if the table is referenced by other database objects (for instance a foreign key constraint). Therefore <productname>PostgreSQL</productname> provides a family of commands to make modifications to existing tables. Note that this is conceptually distinct from altering the data contained in the table: here we are interested in altering the definition, or structure, of the table. テーブルの作成後に間違いに気付いたり、あるいはアプリケーションの要件が変わったりした場合には、テーブルをいったん削除して再度作成できます。 しかし、テーブルにデータを入力済みの場合、あるいはそのテーブルが他のデータベースオブジェクト(例えば外部キー制約)によって参照されている場合、これは良い方法ではありません。 そのため、PostgreSQL では既存のテーブルに変更を加えるための一連のコマンドが用意されています。テーブル内のデータを変更するという概念ではないことに注意してください。 ここでは、テーブルの定義や構造を変更することに焦点を合わせます。

You can: 次のことができます。

All these actions are performed using the <xref linkend="sql-altertable"/> command, whose reference page contains details beyond those given here. これらの操作は全てALTER TABLEコマンド(本節の説明範囲を超えますので詳細はこちらを参照してください)を使用して行うことができます。

5.6.1. 列の追加 #

<title>Adding a Column</title>

To add a column, use a command like: 列を追加するには、次のようなコマンドを使用します。

ALTER TABLE products ADD COLUMN description text;

The new column is initially filled with whatever default value is given (null if you don't specify a <literal>DEFAULT</literal> clause). 新しい列にはデフォルト値が初期値として入ります(DEFAULT句を指定しない場合はNULL値が入ります)。

ヒント

From <productname>PostgreSQL</productname> 11, adding a column with a constant default value no longer means that each row of the table needs to be updated when the <command>ALTER TABLE</command> statement is executed. Instead, the default value will be returned the next time the row is accessed, and applied when the table is rewritten, making the <command>ALTER TABLE</command> very fast even on large tables. PostgreSQL 11から、定数のデフォルト値の列を追加するためにテーブルの各行がALTER TABLE実行時に更新される必要はもうありません。 その代わりに、デフォルト値は次回にその行にアクセスされた場合に返され、テーブルが書き換えられた際に適用されるため、ALTER TABLEは巨大なテーブルでも非常に高速になります。

However, if the default value is volatile (e.g., <function>clock_timestamp()</function>) each row will need to be updated with the value calculated at the time <command>ALTER TABLE</command> is executed. To avoid a potentially lengthy update operation, particularly if you intend to fill the column with mostly nondefault values anyway, it may be preferable to add the column with no default, insert the correct values using <command>UPDATE</command>, and then add any desired default as described below. しかしながら、もしデフォルト値に揮発性(例えば、clock_timestamp())がある場合、各行はALTER TABLE実行時に計算した値に更新される必要があります。 潜在的に長時間の更新作業を避けるため、特に列を主にデフォルト以外の値でとにかく埋めたい場合、デフォルトのない列を追加しUPDATEを使用して正しい値を挿入することが望ましいかもしれません。 その上で、後述するように期待するデフォルトを追加してください。

You can also define constraints on the column at the same time, using the usual syntax: 次の構文を使用すると、列の制約も同時に定義できます。

ALTER TABLE products ADD COLUMN description text CHECK (description <> '');

In fact all the options that can be applied to a column description in <command>CREATE TABLE</command> can be used here. Keep in mind however that the default value must satisfy the given constraints, or the <literal>ADD</literal> will fail. Alternatively, you can add constraints later (see below) after you've filled in the new column correctly. 実際にはCREATE TABLE内の列の記述に使用されている全てのオプションが、ここで使用できます。 ただしデフォルト値は与えられている制約を満足するものでなくてはならないことに注意してください。満足しない場合はADDが失敗します。一方で、新規の列に正しく値を入れた後で制約を追加できます(下記参照)。

5.6.2. 列の削除 #

<title>Removing a Column</title>

To remove a column, use a command like: 列を削除するには、次のようなコマンドを使用します。

ALTER TABLE products DROP COLUMN description;

Whatever data was in the column disappears. Table constraints involving the column are dropped, too. However, if the column is referenced by a foreign key constraint of another table, <productname>PostgreSQL</productname> will not silently drop that constraint. You can authorize dropping everything that depends on the column by adding <literal>CASCADE</literal>: 列内にある、どんなデータであれ消去します。 またその列に関連するテーブルの制約も消去されます。 しかし、その列が他のテーブルの外部キー制約として参照されている場合は、PostgreSQLは暗黙のうちに制約を消去したりはしません。 CASCADEを追加することにより列に依存する全てを消去することを許可できます。

ALTER TABLE products DROP COLUMN description CASCADE;

See <xref linkend="ddl-depend"/> for a description of the general mechanism behind this. この背後にある一般的な仕組みに関する説明は5.14を参照してください。

5.6.3. 制約の追加 #

<title>Adding a Constraint</title>

To add a constraint, the table constraint syntax is used. For example: 制約を追加するには、テーブル制約の構文が使用されます。

ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;

To add a not-null constraint, which cannot be written as a table constraint, use this syntax: 非NULL制約はテーブル制約として記述できないので、追加するには次の構文を使用します。

ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;

The constraint will be checked immediately, so the table data must satisfy the constraint before it can be added. 制約は即座に検査されますので、制約を追加する前にテーブル内のデータがこれに従っている必要があります。

5.6.4. 制約の削除 #

<title>Removing a Constraint</title>

To remove a constraint you need to know its name. If you gave it a name then that's easy. Otherwise the system assigned a generated name, which you need to find out. The <application>psql</application> command <literal>\d <replaceable>tablename</replaceable></literal> can be helpful here; other interfaces might also provide a way to inspect table details. Then the command is: 制約を削除するには、その制約名を知る必要があります。 自分で名前を付けた場合は簡単です。 しかし、自分で名前を付けていない場合はシステム生成の名前が割り当てられているので、それを調べなくてはなりません。 それにはpsql\d tablenameコマンドを使用すると便利です。 他のインタフェースにもテーブルの詳細を調べる方法があるかもしれません。 制約名がわかったら、次のコマンドで制約を削除できます。

ALTER TABLE products DROP CONSTRAINT some_name;

(If you are dealing with a generated constraint name like <literal>$2</literal>, don't forget that you'll need to double-quote it to make it a valid identifier.) (自動生成された$2といった制約名を扱う場合は、有効な識別子となるように二重引用符で括る必要があることを忘れないでください。)

As with dropping a column, you need to add <literal>CASCADE</literal> if you want to drop a constraint that something else depends on. An example is that a foreign key constraint depends on a unique or primary key constraint on the referenced column(s). 列の削除の場合と同じく、何か他のものが依存している制約を削除する場合にはCASCADEを付ける必要があります。 例えば、外部キー制約は、参照されている列の一意または主キー制約に依存しています。

This works the same for all constraint types except not-null constraints. To drop a not null constraint use: 上記は、非NULL制約以外の全ての制約型に適用できます。 非NULL制約を削除するには、次のようにします。

ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

(Recall that not-null constraints do not have names.) (非NULL制約には名前がないことを想起してください。)

5.6.5. 列のデフォルト値の変更 #

<title>Changing a Column's Default Value</title>

To set a new default for a column, use a command like: 列に新しいデフォルトを設定するには、以下のようなコマンドを使用します。

ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;

Note that this doesn't affect any existing rows in the table, it just changes the default for future <command>INSERT</command> commands. これはテーブル内の既存の行には何も影響を与えないことに注意してください。これは将来のINSERTコマンドのために単純にデフォルトを変えるだけです。

To remove any default value, use: デフォルト値を削除するには次のようにします。

ALTER TABLE products ALTER COLUMN price DROP DEFAULT;

This is effectively the same as setting the default to null. As a consequence, it is not an error to drop a default where one hadn't been defined, because the default is implicitly the null value. これは、デフォルトをNULLに設定することと同等です。 そのため、定義されていないデフォルト値を削除してもエラーにはなりません。 なぜなら NULL値が暗黙的にデフォルトとなっているからです。

5.6.6. 列のデータ型の変更 #

<title>Changing a Column's Data Type</title>

To convert a column to a different data type, use a command like: 列を異なるデータ型に変換するには以下のようなコマンドを使用してください。

ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);

This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a <literal>USING</literal> clause that specifies how to compute the new values from the old. これは、その列の既存の項目が新しい型に暗黙的キャストにより変換できる場合にのみ成功します。 より複雑な変換が必要な場合、古い値から新しい値をどのように計算するかを指定するUSING句を付けることができます。

<productname>PostgreSQL</productname> will attempt to convert the column's default value (if any) to the new type, as well as any constraints that involve the column. But these conversions might fail, or might produce surprising results. It's often best to drop any constraints on the column before altering its type, and then add back suitably modified constraints afterwards. PostgreSQLは、(もしあれば)列のデフォルト値を新しい型に、同時に、その列に関連する全ての制約も新しい型に変換しようとします。 しかし、こうした変換は失敗するかもしれませんし、予想を超えた結果になってしまうかもしれません。 型を変更する前にその列に関する制約を全て削除し、後で適切に変更した制約を付け直すことが最善な場合がよくあります。

5.6.7. 列名の変更 #

<title>Renaming a Column</title>

To rename a column: 列名を変更するには、次のようにします。

ALTER TABLE products RENAME COLUMN product_no TO product_number;

5.6.8. テーブル名の変更 #

<title>Renaming a Table</title>

To rename a table: テーブル名を変更するには、次のようにします。

ALTER TABLE products RENAME TO items;