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

ALTER TABLE

ALTER TABLE <refpurpose>change the definition of a table</refpurpose> — テーブル定義を変更する

概要

ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
    action [, ... ]
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
    RENAME [ COLUMN ] column_name TO new_column_name
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
    RENAME CONSTRAINT constraint_name TO new_constraint_name
ALTER TABLE [ IF EXISTS ] name
    RENAME TO new_name
ALTER TABLE [ IF EXISTS ] name
    SET SCHEMA new_schema
ALTER TABLE ALL IN TABLESPACE name [ OWNED BY role_name [, ... ] ]
    SET TABLESPACE new_tablespace [ NOWAIT ]
ALTER TABLE [ IF EXISTS ] name
    ATTACH PARTITION partition_name { FOR VALUES partition_bound_spec | DEFAULT }
ALTER TABLE [ IF EXISTS ] name
    DETACH PARTITION partition_name [ CONCURRENTLY | FINALIZE ]


<phrase>where <replaceable class="parameter">action</replaceable> is one of:</phrase>

ここで、actionは以下のいずれかです。

    ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
    DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
    ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
    ALTER [ COLUMN ] column_name SET DEFAULT expression
    ALTER [ COLUMN ] column_name DROP DEFAULT
    ALTER [ COLUMN ] column_name { SET | DROP } NOT NULL
    ALTER [ COLUMN ] column_name DROP EXPRESSION [ IF EXISTS ]
    ALTER [ COLUMN ] column_name ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]
    ALTER [ COLUMN ] column_name { SET GENERATED { ALWAYS | BY DEFAULT } | SET sequence_option | RESTART [ [ WITH ] restart ] } [...]
    ALTER [ COLUMN ] column_name DROP IDENTITY [ IF EXISTS ]
    ALTER [ COLUMN ] column_name SET STATISTICS integer
    ALTER [ COLUMN ] column_name SET ( attribute_option = value [, ... ] )
    ALTER [ COLUMN ] column_name RESET ( attribute_option [, ... ] )
    ALTER [ COLUMN ] column_name SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT }
    ALTER [ COLUMN ] column_name SET COMPRESSION compression_method
    ADD table_constraint [ NOT VALID ]
    ADD table_constraint_using_index
    ALTER CONSTRAINT constraint_name [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
    VALIDATE CONSTRAINT constraint_name
    DROP CONSTRAINT [ IF EXISTS ]  constraint_name [ RESTRICT | CASCADE ]
    DISABLE TRIGGER [ trigger_name | ALL | USER ]
    ENABLE TRIGGER [ trigger_name | ALL | USER ]
    ENABLE REPLICA TRIGGER trigger_name
    ENABLE ALWAYS TRIGGER trigger_name
    DISABLE RULE rewrite_rule_name
    ENABLE RULE rewrite_rule_name
    ENABLE REPLICA RULE rewrite_rule_name
    ENABLE ALWAYS RULE rewrite_rule_name
    DISABLE ROW LEVEL SECURITY
    ENABLE ROW LEVEL SECURITY
    FORCE ROW LEVEL SECURITY
    NO FORCE ROW LEVEL SECURITY
    CLUSTER ON index_name
    SET WITHOUT CLUSTER
    SET WITHOUT OIDS
    SET ACCESS METHOD new_access_method
    SET TABLESPACE new_tablespace
    SET { LOGGED | UNLOGGED }
    SET ( storage_parameter [= value] [, ... ] )
    RESET ( storage_parameter [, ... ] )
    INHERIT parent_table
    NO INHERIT parent_table
    OF type_name
    NOT OF
    OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }
    REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING }


<phrase>and <replaceable class="parameter">partition_bound_spec</replaceable> is:</phrase>

また、partition_bound_specは以下のいずれかです。

IN ( partition_bound_expr [, ...] ) |
FROM ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] )
  TO ( { partition_bound_expr | MINVALUE | MAXVALUE } [, ...] ) |
WITH ( MODULUS numeric_literal, REMAINDER numeric_literal )


<phrase>and <replaceable class="parameter">column_constraint</replaceable> is:</phrase>

また、column_constraintは以下の通りです。

[ CONSTRAINT constraint_name ]
{ NOT NULL |
  NULL |
  CHECK ( expression ) [ NO INHERIT ] |
  DEFAULT default_expr |
  GENERATED ALWAYS AS ( generation_expr ) STORED |
  GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ] |
  UNIQUE [ NULLS [ NOT ] DISTINCT ] index_parameters |
  PRIMARY KEY index_parameters |
  REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
    [ ON DELETE referential_action ] [ ON UPDATE referential_action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]


<phrase>and <replaceable class="parameter">table_constraint</replaceable> is:</phrase>

また、table_constraintは以下の通りです。

[ CONSTRAINT constraint_name ]
{ CHECK ( expression ) [ NO INHERIT ] |
  UNIQUE [ NULLS [ NOT ] DISTINCT ] ( column_name [, ... ] ) index_parameters |
  PRIMARY KEY ( column_name [, ... ] ) index_parameters |
  EXCLUDE [ USING index_method ] ( exclude_element WITH operator [, ... ] ) index_parameters [ WHERE ( predicate ) ] |
  FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
    [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE referential_action ] [ ON UPDATE referential_action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]


<phrase>and <replaceable class="parameter">table_constraint_using_index</replaceable> is:</phrase>

またtable_constraint_using_indexは以下の通りです。

    [ CONSTRAINT constraint_name ]
    { UNIQUE | PRIMARY KEY } USING INDEX index_name
    [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]


<phrase><replaceable class="parameter">index_parameters</replaceable> in <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and <literal>EXCLUDE</literal> constraints are:</phrase>

UNIQUEPRIMARY KEY、および、EXCLUDE制約でのindex_parametersは以下の通りです。

[ INCLUDE ( column_name [, ... ] ) ]
[ WITH ( storage_parameter [= value] [, ... ] ) ]
[ USING INDEX TABLESPACE tablespace_name ]


<phrase><replaceable class="parameter">exclude_element</replaceable> in an <literal>EXCLUDE</literal> constraint is:</phrase>

EXCLUDE制約でのexclude_elementは以下の通りです。

{ column_name | ( expression ) } [ opclass ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]

referential_action in a FOREIGN KEY/REFERENCES constraint is:

{ NO ACTION | RESTRICT | CASCADE | SET NULL [ ( column_name [, ... ] ) ] | SET DEFAULT [ ( column_name [, ... ] ) ] }

説明

<title>Description</title>

<command>ALTER TABLE</command> changes the definition of an existing table. There are several subforms described below. Note that the lock level required may differ for each subform. An <literal>ACCESS EXCLUSIVE</literal> lock is acquired unless explicitly noted. When multiple subcommands are given, the lock acquired will be the strictest one required by any subcommand. ALTER TABLEは既存のテーブルの定義を変更します。 以下のようにいくつかの副構文があります。 要求されるロックレベルはそれぞれの副構文によって異なることに注意してください。 特に記述がなければACCESS EXCLUSIVEロックを取得します。 複数のサブコマンドが使われるときは、それらのサブコマンドが要求するうち、もっとも高いレベルのロックを取得します。

ADD COLUMN [ IF NOT EXISTS ] #

This form adds a new column to the table, using the same syntax as <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. If <literal>IF NOT EXISTS</literal> is specified and a column already exists with this name, no error is thrown. この構文を使用すると、CREATE TABLEと同じ構文を使って新しい列をテーブルに追加できます。 IF NOT EXISTSが指定され、その名前の列が既に存在している場合は、エラーが発生しません。

DROP COLUMN [ IF EXISTS ] #

This form drops a column from a table. Indexes and table constraints involving the column will be automatically dropped as well. Multivariate statistics referencing the dropped column will also be removed if the removal of the column would cause the statistics to contain data for only a single column. You will need to say <literal>CASCADE</literal> if anything outside the table depends on the column, for example, foreign key references or views. If <literal>IF EXISTS</literal> is specified and the column does not exist, no error is thrown. In this case a notice is issued instead. この構文を使用すると、テーブルから列を削除できます。 削除する列を含んでいるインデックスおよびテーブル制約も自動的に削除されます。 削除する列を参照する多変量統計がある場合、列の削除の結果、その統計が1つの列のデータしか含まないようになるなら、それも削除されます。 また、削除する列にテーブル以外が依存(例えば、外部キー制約、ビューなど)している場合、CASCADEを付ける必要があります。 IF EXISTSが指定されている場合、もしその列がなかったとしてもエラーにはなりません。 この場合は代わりに注意が出力されます。

SET DATA TYPE #

This form changes the type of a column of a table. Indexes and simple table constraints involving the column will be automatically converted to use the new column type by reparsing the originally supplied expression. The optional <literal>COLLATE</literal> clause specifies a collation for the new column; if omitted, the collation is the default for the new column type. The optional <literal>USING</literal> clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A <literal>USING</literal> clause must be provided if there is no implicit or assignment cast from old to new type. この構文を使用すると、テーブルの列の型を変更できます。 その列を含むインデックスと簡単なテーブル制約は、元々与えられた式を再解析し、新しい型を使用するように自動的に変換されます。 COLLATE句を使うと、新しい列の照合順を指定できます。 省略時の照合順は新しい列の型のデフォルトになります。 USING句を使うと、古い列値をどのように新しい値に計算するかを指定できます。 省略された場合、デフォルトの変換は、古いデータ型から新しいデータ型への代入キャストと同じになります。 古いデータ型から新しいデータ型への暗黙キャストあるいは代入キャストがない場合、USING句を指定しなければなりません。

When this form is used, the column's statistics are removed, so running <link linkend="sql-analyze"><command>ANALYZE</command></link> on the table afterwards is recommended. この形式を使用すると、列の統計情報が削除されるので、後でテーブルに対してANALYZEを実行することをお勧めします。

SET/DROP DEFAULT #

These forms set or remove the default value for a column (where removal is equivalent to setting the default value to NULL). The new default value will only apply in subsequent <command>INSERT</command> or <command>UPDATE</command> commands; it does not cause rows already in the table to change. これらの構文を使用すると、列のデフォルト値を設定または削除できます(ここで、削除はデフォルト値をNULLに設定することと等価です)。 新しいデフォルト値は、変更後に行われるINSERTまたはUPDATEコマンドにのみ適用されます。 テーブル内の既存の行は変更されません。

SET/DROP NOT NULL #

These forms change whether a column is marked to allow null values or to reject null values. これらの構文は、列の値としてNULL値を認めるか拒絶するかを変更します。

<literal>SET NOT NULL</literal> may only be applied to a column provided none of the records in the table contain a <literal>NULL</literal> value for the column. Ordinarily this is checked during the <literal>ALTER TABLE</literal> by scanning the entire table; however, if a valid <literal>CHECK</literal> constraint is found which proves no <literal>NULL</literal> can exist, then the table scan is skipped. SET NOT NULLは、テーブルの項目でその列がNULL値であるものが1つもない場合にのみ、その列に設定可能です。 通常これはALTER TABLEがテーブル全体をスキャンする際に確認されます。しかしながら、NULLが存在できないことを示す有効なCHECK制約が見つかれば、テーブルスキャンは省略されます。

If this table is a partition, one cannot perform <literal>DROP NOT NULL</literal> on a column if it is marked <literal>NOT NULL</literal> in the parent table. To drop the <literal>NOT NULL</literal> constraint from all the partitions, perform <literal>DROP NOT NULL</literal> on the parent table. Even if there is no <literal>NOT NULL</literal> constraint on the parent, such a constraint can still be added to individual partitions, if desired; that is, the children can disallow nulls even if the parent allows them, but not the other way around. このテーブルがパーティションの場合、親テーブルでNOT NULLの印がつけられている列についてDROP NOT NULLを実行することはできません。 すべてのパーティションからNOT NULL制約を削除するには、親テーブルでDROP NOT NULLを実行してください。 親テーブルにNOT NULL制約がない場合でも、望むなら各パーティションにそのような制約を追加することができます。 つまり、親テーブルがNULLを許していても子テーブルでNULLを禁止することができますが、その逆はできません。

DROP EXPRESSION [ IF EXISTS ] #

This form turns a stored generated column into a normal base column. Existing data in the columns is retained, but future changes will no longer apply the generation expression. この構文は、格納された生成列を通常の基本列に変換します。 列の既存のデータは保持されますが、以後の変更はもはや生成式を適用しません。

If <literal>DROP EXPRESSION IF EXISTS</literal> is specified and the column is not a stored generated column, no error is thrown. In this case a notice is issued instead. DROP EXPRESSION IF EXISTSが指定され、その列が格納された生成列でない場合は、エラーを発生させません。 この場合、注意メッセージが発行されます。

ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY
SET GENERATED { ALWAYS | BY DEFAULT }
DROP IDENTITY [ IF EXISTS ] #

These forms change whether a column is an identity column or change the generation attribute of an existing identity column. See <link linkend="sql-createtable"><command>CREATE TABLE</command></link> for details. Like <literal>SET DEFAULT</literal>, these forms only affect the behavior of subsequent <command>INSERT</command> and <command>UPDATE</command> commands; they do not cause rows already in the table to change. この構文では、列がIDENTITY列であるかどうか、または既存のIDENTITY列の生成属性を変更することができます。 詳細はCREATE TABLEを参照してください。 SET DEFAULT同様に、この構文は、変更後に行われるINSERTまたはUPDATEコマンドにのみ適用されます。 テーブル内の既存の行は変更されません。

If <literal>DROP IDENTITY IF EXISTS</literal> is specified and the column is not an identity column, no error is thrown. In this case a notice is issued instead. DROP IDENTITY IF EXISTSが指定され、その列がIDENTITY列でない場合は、エラーを発生させません。 この場合、注意メッセージが発行されます。

SET sequence_option
RESTART #

These forms alter the sequence that underlies an existing identity column. <replaceable>sequence_option</replaceable> is an option supported by <link linkend="sql-altersequence"><command>ALTER SEQUENCE</command></link> such as <literal>INCREMENT BY</literal>. この構文では、既存のIDENTITY列に紐付けられているシーケンスを変更します。 sequence_optionINCREMENT BYなどALTER SEQUENCEがサポートするオプションです。

SET STATISTICS #

This form sets the per-column statistics-gathering target for subsequent <link linkend="sql-analyze"><command>ANALYZE</command></link> operations. The target can be set in the range 0 to 10000; alternatively, set it to -1 to revert to using the system default statistics target (<xref linkend="guc-default-statistics-target"/>). For more information on the use of statistics by the <productname>PostgreSQL</productname> query planner, refer to <xref linkend="planner-stats"/>. この構文は、以後のANALYZE操作において、列単位での統計情報収集対象を設定します。 対象として、0から10000までの範囲の値を設定可能です。 また、対象を-1に設定すると、システムのデフォルト統計情報対象(default_statistics_target)が使用されます。 PostgreSQLの問い合わせプランナによる統計情報の使用に関する詳細は、14.2を参照してください。

<literal>SET STATISTICS</literal> acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. SET STATISTICSSHARE UPDATE EXCLUSIVEロックを取得します。

SET ( attribute_option = value [, ... ] )
RESET ( attribute_option [, ... ] ) #

This form sets or resets per-attribute options. Currently, the only defined per-attribute options are <literal>n_distinct</literal> and <literal>n_distinct_inherited</literal>, which override the number-of-distinct-values estimates made by subsequent <link linkend="sql-analyze"><command>ANALYZE</command></link> operations. <literal>n_distinct</literal> affects the statistics for the table itself, while <literal>n_distinct_inherited</literal> affects the statistics gathered for the table plus its inheritance children. When set to a positive value, <command>ANALYZE</command> will assume that the column contains exactly the specified number of distinct nonnull values. When set to a negative value, which must be greater than or equal to -1, <command>ANALYZE</command> will assume that the number of distinct nonnull values in the column is linear in the size of the table; the exact count is to be computed by multiplying the estimated table size by the absolute value of the given number. For example, a value of -1 implies that all values in the column are distinct, while a value of -0.5 implies that each value appears twice on the average. This can be useful when the size of the table changes over time, since the multiplication by the number of rows in the table is not performed until query planning time. Specify a value of 0 to revert to estimating the number of distinct values normally. For more information on the use of statistics by the <productname>PostgreSQL</productname> query planner, refer to <xref linkend="planner-stats"/>. この構文は属性単位のオプションの設定または設定解除を行います。 現時点では属性単位のオプションで定義されているのはn_distinctおよびn_distinct_inheritedのみです。 これらのオプションは、その後のANALYZE操作により生成される個別値数の推定値を上書きします。 n_distinctはテーブル自身の統計情報に影響を与え、n_distinct_inheritedはテーブルとそれを継承した子テーブルから集めた統計情報に影響を与えます。 正の値の場合、ANALYZEは、その列には、正確に指定された個数の非NULLの個別値が存在するものとみなします。 負の値の場合、この値は-1以上でなければなりませんが、ANALYZEは、その列内の非NULLの個別値はテーブルのサイズに線形であるとみなし、推定テーブルサイズに指定した値の絶対値を乗じた値が個別値数であるとみなします。 たとえば、-1という値は、列内のすべての値に重複がないことを意味し、-0.5という値は個々の値は平均して2回現れることを意味します。 テーブルの行数との乗算は問い合わせ計画を作成するまで行われませんので、テーブルサイズが変わり続けるような場合にこれは有用かもしれません。 0という値を指定することで、個別値数の推定を通常に戻します。 PostgreSQL問い合わせプランナにおける統計情報の使用に関しては14.2を参照してください。

Changing per-attribute options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. 属性単位のオプションの変更はSHARE UPDATE EXCLUSIVEロックを取得します。

SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT } #

This form sets the storage mode for a column. This controls whether this column is held inline or in a secondary <acronym>TOAST</acronym> table, and whether the data should be compressed or not. <literal>PLAIN</literal> must be used for fixed-length values such as <type>integer</type> and is inline, uncompressed. <literal>MAIN</literal> is for inline, compressible data. <literal>EXTERNAL</literal> is for external, uncompressed data, and <literal>EXTENDED</literal> is for external, compressed data. Writing <literal>DEFAULT</literal> sets the storage mode to the default mode for the column's data type. <literal>EXTENDED</literal> is the default for most data types that support non-<literal>PLAIN</literal> storage. Use of <literal>EXTERNAL</literal> will make substring operations on very large <type>text</type> and <type>bytea</type> values run faster, at the penalty of increased storage space. Note that <literal>ALTER TABLE ... SET STORAGE</literal> doesn't itself change anything in the table; it just sets the strategy to be pursued during future table updates. See <xref linkend="storage-toast"/> for more information. この構文は、列の格納モードを設定します。 列をインラインで保持するか補助TOASTテーブルに保持するか、また、データを圧縮するかどうかを制御できます。 PLAINは、integerのような固定長の値に対して使用します。インラインで保持され、圧縮されません。 MAINは、インラインで保持されていて、圧縮可能なデータに使用します。 EXTERNALは圧縮されていない外部データに使用します。 EXTENDEDは圧縮された外部データに使用します。 DEFAULTと書くと、列のデータ型に対して格納モードをデフォルトのモードに設定します。 EXTENDEDは、PLAIN以外の保管をサポートするほとんどのデータ型におけるデフォルトです。 EXTERNALを使用すると、非常に長いtextおよびbytea列に対する部分文字列操作の処理速度が向上しますが、必要な保管容量が増えるというデメリットがあります。 ALTER TABLE ... SET STORAGE自体はテーブルをまったく変更しないことに注意してください。 以後のテーブルの更新時に遂行する戦略を設定するだけです。 詳細は73.2を参照してください。

SET COMPRESSION compression_method #

This form sets the compression method for a column, determining how values inserted in future will be compressed (if the storage mode permits compression at all). This does not cause the table to be rewritten, so existing data may still be compressed with other compression methods. If the table is restored with <application>pg_restore</application>, then all values are rewritten with the configured compression method. However, when data is inserted from another relation (for example, by <command>INSERT ... SELECT</command>), values from the source table are not necessarily detoasted, so any previously compressed data may retain its existing compression method, rather than being recompressed with the compression method of the target column. The supported compression methods are <literal>pglz</literal> and <literal>lz4</literal>. (<literal>lz4</literal> is available only if <option>&#45;-with-lz4</option> was used when building <productname>PostgreSQL</productname>.) In addition, <replaceable class="parameter">compression_method</replaceable> can be <literal>default</literal>, which selects the default behavior of consulting the <xref linkend="guc-default-toast-compression"/> setting at the time of data insertion to determine the method to use. この構文を使用すると、列の圧縮方式を設定し、将来挿入される値がどのように圧縮されるかを決定できます(格納モードで圧縮が許可されている場合)。 これによってテーブルが書き換えられることはないため、既存のデータは他の圧縮方式で圧縮されたままの可能性があります。 テーブルをpg_restoreでリストアした場合、すべての値は設定された圧縮方式で書き直されます。 しかし、データが別のリレーションから挿入された場合(例えばINSERT ... SELECTによって)、ソーステーブルからの値は必ずしも非TOAST化されるとは限らないため、以前に圧縮されたデータは、ターゲット列の圧縮方式で再圧縮されるのではなく、既存の圧縮方式を保持する場合があります。 サポートされている圧縮方式は、pglzlz4です(lz4は、PostgreSQLのビルド時に--with-lz4が使用された場合にのみ使用できます)。 さらに、compression_methoddefaultにすることができ、これにより、データ挿入時にdefault_toast_compression設定を参照して、使用する方法を決定するデフォルトの動作が選択されます。

ADD table_constraint [ NOT VALID ] #

This form adds a new constraint to a table using the same constraint syntax as <link linkend="sql-createtable"><command>CREATE TABLE</command></link>, plus the option <literal>NOT VALID</literal>, which is currently only allowed for foreign key and CHECK constraints. この構文は、CREATE TABLEと同じ制約構文に加え、現時点では外部キー制約と検査制約でのみ許されるNOT VALIDオプションを使って新しい制約をテーブルに追加します。

Normally, this form will cause a scan of the table to verify that all existing rows in the table satisfy the new constraint. But if the <literal>NOT VALID</literal> option is used, this potentially-lengthy scan is skipped. The constraint will still be enforced against subsequent inserts or updates (that is, they'll fail unless there is a matching row in the referenced table, in the case of foreign keys, or they'll fail unless the new row matches the specified check condition). But the database will not assume that the constraint holds for all rows in the table, until it is validated by using the <literal>VALIDATE CONSTRAINT</literal> option. See <xref linkend="sql-altertable-notes"/> below for more information about using the <literal>NOT VALID</literal> option. 通常この構文は、テーブルの既存の行が新しい制約を満たすか確認するため、テーブルのスキャンの原因となります。 しかし、NOT VALIDオプションが使われていれば、時間がかかるかもしれないこのスキャンは省略されます。 それでも、制約はその後の挿入や更新に対して強制されます(つまり、外部キー制約の場合、被参照テーブルに一致する行が存在しない限り失敗します。指定された検査制約に一致する新しい行が存在しない限り失敗します)。 しかしデータベースは、VALIDATE CONSTRAINTオプションを使用して検証されるまで、テーブル内のすべての行で制約が保持されているとみなしません。 NOT VALIDオブションを使うことに関する更なる情報は注釈以下を参照してください。

Although most forms of <literal>ADD <replaceable class="parameter">table_constraint</replaceable></literal> require an <literal>ACCESS EXCLUSIVE</literal> lock, <literal>ADD FOREIGN KEY</literal> requires only a <literal>SHARE ROW EXCLUSIVE</literal> lock. Note that <literal>ADD FOREIGN KEY</literal> also acquires a <literal>SHARE ROW EXCLUSIVE</literal> lock on the referenced table, in addition to the lock on the table on which the constraint is declared. ADD table_constraintのほとんどの構文ではACCESS EXCLUSIVEロックが必要ですが、ADD FOREIGN KEYではSHARE ROW EXCLUSIVEロックだけが必要です。 ADD FOREIGN KEYは、制約を宣言したテーブルでのロックに加えて、被参照テーブルのSHARE ROW EXCLUSIVEロックも取得することに注意してください。

Additional restrictions apply when unique or primary key constraints are added to partitioned tables; see <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. Also, foreign key constraints on partitioned tables may not be declared <literal>NOT VALID</literal> at present. 一意性制約や主キー制約がパーティションテーブルに追加されるときには、追加的な制限が適用されます。 CREATE TABLEを参照してください。 また、今のところ、パーティションテーブルでの外部キー制約ではNOT VALIDと宣言できません。

ADD table_constraint_using_index #

This form adds a new <literal>PRIMARY KEY</literal> or <literal>UNIQUE</literal> constraint to a table based on an existing unique index. All the columns of the index will be included in the constraint. この構文は、既存の一意性インデックスに基づき、テーブルにPRIMARY KEYまたはUNIQUE制約を新たに追加します。 インデックスのすべての列がこの制約に含まれます。

The index cannot have expression columns nor be a partial index. Also, it must be a b-tree index with default sort ordering. These restrictions ensure that the index is equivalent to one that would be built by a regular <literal>ADD PRIMARY KEY</literal> or <literal>ADD UNIQUE</literal> command. このインデックスは式列を持つことはできず、また部分インデックスであってはいけません。 またこれはデフォルトのソート順序を持つB-Treeインデックスでなければなりません。 これらの制限により、このインデックスが通常のADD PRIMARY KEYまたはADD UNIQUEコマンドにより構築されたインデックスと等価であることを確実にします。

If <literal>PRIMARY KEY</literal> is specified, and the index's columns are not already marked <literal>NOT NULL</literal>, then this command will attempt to do <literal>ALTER COLUMN SET NOT NULL</literal> against each such column. That requires a full table scan to verify the column(s) contain no nulls. In all other cases, this is a fast operation. PRIMARY KEYが指定され、インデックスの列がNOT NULLと印付けされていない場合、このコマンドはこうした列のそれぞれに対してALTER COLUMN SET NOT NULLの実施を試みます。 これは列にNULLが含まれないことを検証するために完全なテーブルスキャンを必要とします。 この他の場合においては、これが高速な操作です。

If a constraint name is provided then the index will be renamed to match the constraint name. Otherwise the constraint will be named the same as the index. 制約名が提供された場合、インデックスの名前は制約名に合うように変更されます。 提供されない場合は制約にはインデックスと同じ名前が付けられます。

After this command is executed, the index is <quote>owned</quote> by the constraint, in the same way as if the index had been built by a regular <literal>ADD PRIMARY KEY</literal> or <literal>ADD UNIQUE</literal> command. In particular, dropping the constraint will make the index disappear too. このコマンドの実行後、インデックスは、制約により所有され、それはインデックスが通常のADD PRIMARY KEYまたはADD UNIQUEにより構築された場合と同様です。 特にこの制約を削除するとインデックスも消えてしまいます。

This form is not currently supported on partitioned tables. この形式は今のところパーティションテーブルではサポートされません。

注記

Adding a constraint using an existing index can be helpful in situations where a new constraint needs to be added without blocking table updates for a long time. To do that, create the index using <command>CREATE INDEX CONCURRENTLY</command>, and then install it as an official constraint using this syntax. See the example below. 既存のインデックスを使用した制約の追加は、テーブル更新を長時間ブロックすることなく新しい制約を追加しなければならない場合に有用になる可能性があります。 このためには、CREATE INDEX CONCURRENTLYを用いてインデックスを作成し、この構文を使用して正式の制約としてインストールしてください。 後述の例を参照してください。

ALTER CONSTRAINT #

This form alters the attributes of a constraint that was previously created. Currently only foreign key constraints may be altered. この構文は以前に作成された制約の属性を変更します。 現在は外部キー制約のみを変更できます。

VALIDATE CONSTRAINT #

This form validates a foreign key or check constraint that was previously created as <literal>NOT VALID</literal>, by scanning the table to ensure there are no rows for which the constraint is not satisfied. Nothing happens if the constraint is already marked valid. (See <xref linkend="sql-altertable-notes"/> below for an explanation of the usefulness of this command.) この構文は、以前にNOT VALIDとして作成された外部キー制約または検査制約を、これらの制約を満たさない行が存在しないことを確認するためにテーブルをスキャンして、検証します。 制約がすでに有効であると記録されている場合は何も起こりません。 (このコマンドの有用性の説明は注釈以下を参照してください。)

This command acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. このコマンドはSHARE UPDATE EXCLUSIVEロックを取得します。

DROP CONSTRAINT [ IF EXISTS ] #

This form drops the specified constraint on a table, along with any index underlying the constraint. If <literal>IF EXISTS</literal> is specified and the constraint does not exist, no error is thrown. In this case a notice is issued instead. この構文はテーブル上の指定した制約を、制約の基となるインデックスと共に削除します。 IF EXISTSが指定された場合、その制約がなくてもエラーになりません。 この場合は代わりに注意が出力されます。

DISABLE/ENABLE [ REPLICA | ALWAYS ] TRIGGER #

These forms configure the firing of trigger(s) belonging to the table. A disabled trigger is still known to the system, but is not executed when its triggering event occurs. (For a deferred trigger, the enable status is checked when the event occurs, not when the trigger function is actually executed.) One can disable or enable a single trigger specified by name, or all triggers on the table, or only user triggers (this option excludes internally generated constraint triggers, such as those that are used to implement foreign key constraints or deferrable uniqueness and exclusion constraints). Disabling or enabling internally generated constraint triggers requires superuser privileges; it should be done with caution since of course the integrity of the constraint cannot be guaranteed if the triggers are not executed. この構文を使用すると、テーブルに属するトリガの発行について設定できます。 無効にされたトリガはシステム上に存在し続けますが、トリガイベントが発生したとしても実行されません。 (遅延トリガの場合、有効無効状態の確認は、トリガ関数を実際に実行しようとする時ではなく、イベントの発生時に行われます。) 名前でトリガを1つ指定して有効または無効にすることもできますし、テーブル上のすべてのトリガを有効または無効にすることもできます。 また、ユーザトリガのみを有効または無効にすることも可能です (このオプションは、外部キー制約、遅延可能な一意性および排他制約を実装するために使用される内部向けに生成される制約トリガを除外します。) 内部向けに生成される制約トリガを有効または無効にするにはスーパーユーザ権限が必要です。 トリガが実行されなかった場合は当然ながら制約の整合性が保証されませんので、制約トリガの無効化は注意して実行しなければなりません。

The trigger firing mechanism is also affected by the configuration variable <xref linkend="guc-session-replication-role"/>. Simply enabled triggers (the default) will fire when the replication role is <quote>origin</quote> (the default) or <quote>local</quote>. Triggers configured as <literal>ENABLE REPLICA</literal> will only fire if the session is in <quote>replica</quote> mode, and triggers configured as <literal>ENABLE ALWAYS</literal> will fire regardless of the current replication role. トリガ発行機構は設定変数session_replication_roleの影響も受けます。 単に有効としたトリガ(デフォルト)では、レプリケーションロールがorigin(デフォルト)またはlocalの場合に発行されます。 ENABLE REPLICAと設定されたトリガでは、セッションがreplicaモードである場合のみ発行されます。 そして、ENABLE ALWAYSと設定されたトリガでは、現在のレプリケーションロールに関係なく発行されます。

The effect of this mechanism is that in the default configuration, triggers do not fire on replicas. This is useful because if a trigger is used on the origin to propagate data between tables, then the replication system will also replicate the propagated data; so the trigger should not fire a second time on the replica, because that would lead to duplication. However, if a trigger is used for another purpose such as creating external alerts, then it might be appropriate to set it to <literal>ENABLE ALWAYS</literal> so that it is also fired on replicas. この仕組みの効果はデフォルト設定ではレプリカ上でトリガが発行しないことです。 トリガがオリジンでテーブル間でデータを伝播するのに使われている場合にレプリケーションシステムは伝播したデータもレプリケーションします。レプリカ上でトリガが再度発動すべきではありませんので、これは有用です。 しかしながら、トリガが外部的な警告を発するなどの他の意図で使われている場合、レプリカでもトリガが発行されるようにENABLE ALWAYSを設定するのが適切と言えます。

When this command is applied to a partitioned table, the states of corresponding clone triggers in the partitions are updated too, unless <literal>ONLY</literal> is specified. このコマンドがパーティション化されたテーブルに適用されると、ONLYが指定されていない限り、パーティション内の対応するクローントリガの状態も更新されます。

This command acquires a <literal>SHARE ROW EXCLUSIVE</literal> lock. このコマンドはSHARE ROW EXCLUSIVEロックを取得します。

DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE #

These forms configure the firing of rewrite rules belonging to the table. A disabled rule is still known to the system, but is not applied during query rewriting. The semantics are as for disabled/enabled triggers. This configuration is ignored for <literal>ON SELECT</literal> rules, which are always applied in order to keep views working even if the current session is in a non-default replication role. この構文を使用すると、テーブルに属する書き換えルールの実行について設定することができます。 ルールは無効にしてもシステムに残りますが、問い合わせ書き換え時に適用されません。 この意味はトリガの有効化、無効化と同じです。 この設定はON SELECTルールでは無視されます。 現在のセッションがデフォルト以外のレプリケーションモードであったとしても、ビュー操作を維持するために常に適用されます。

The rule firing mechanism is also affected by the configuration variable <xref linkend="guc-session-replication-role"/>, analogous to triggers as described above. 前述のトリガと同様に、ルール発行機構は設定変数session_replication_roleの影響を受けます。

DISABLE/ENABLE ROW LEVEL SECURITY #

These forms control the application of row security policies belonging to the table. If enabled and no policies exist for the table, then a default-deny policy is applied. Note that policies can exist for a table even if row-level security is disabled. In this case, the policies will <emphasis>not</emphasis> be applied and the policies will be ignored. See also <link linkend="sql-createpolicy"><command>CREATE POLICY</command></link>. これらの構文は、テーブルの行セキュリティポリシーの適用を制御します。 有効にされ、かつテーブルにポリシーが存在しない場合は、デフォルトの拒絶ポリシーが適用されます。 行単位セキュリティが無効になっている場合でも、テーブルのセキュリティが存在し得ることに注意してください。 この場合、ポリシーは適用されず、無視されます。 CREATE POLICYも参照してください。

NO FORCE/FORCE ROW LEVEL SECURITY #

These forms control the application of row security policies belonging to the table when the user is the table owner. If enabled, row-level security policies will be applied when the user is the table owner. If disabled (the default) then row-level security will not be applied when the user is the table owner. See also <link linkend="sql-createpolicy"><command>CREATE POLICY</command></link>. これらの構文は、ユーザがテーブルの所有者である場合について、テーブルの行セキュリティポリシーの適用を制御します。 有効の場合、ユーザがテーブルの所有者であれば、行セキュリティポリシーが適用されます。 無効(デフォルト)の場合、ユーザがテーブルの所有者であれば、行セキュリティポリシーは適用されません。 CREATE POLICYも参照してください。

CLUSTER ON #

This form selects the default index for future <link linkend="sql-cluster"><command>CLUSTER</command></link> operations. It does not actually re-cluster the table. この構文は、以後のCLUSTER操作用のデフォルトインデックスを選択します。 テーブルの再クラスタ化は実際には行いません。

Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. clusterオプションの変更はSHARE UPDATE EXCLUSIVEロックを取得します。

SET WITHOUT CLUSTER #

This form removes the most recently used <link linkend="sql-cluster"><command>CLUSTER</command></link> index specification from the table. This affects future cluster operations that don't specify an index. この構文は、テーブルから、一番最後に適用されたCLUSTERインデックス指定を削除します。 以後のインデックスを指定しないクラスタ操作に影響を及ぼします。

Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock. clusterオプションの変更はSHARE UPDATE EXCLUSIVEロックを取得します。

SET WITHOUT OIDS #

Backward-compatible syntax for removing the <literal>oid</literal> system column. As <literal>oid</literal> system columns cannot be added anymore, this never has an effect. システム列oidを削除する、後方互換のための構文です。 システム列oidは今では追加できませんので、これは効果がありません。

SET ACCESS METHOD #

This form changes the access method of the table by rewriting it. See <xref linkend="tableam"/> for more information. この形式は、テーブルのアクセスメソッドを書き換えることにより変更します。 詳細は第63章を参照してください。

SET TABLESPACE #

This form changes the table's tablespace to the specified tablespace and moves the data file(s) associated with the table to the new tablespace. Indexes on the table, if any, are not moved; but they can be moved separately with additional <literal>SET TABLESPACE</literal> commands. When applied to a partitioned table, nothing is moved, but any partitions created afterwards with <command>CREATE TABLE PARTITION OF</command> will use that tablespace, unless overridden by a <literal>TABLESPACE</literal> clause. この構文を使用すると、テーブルのテーブル空間を指定したテーブル空間に変更し、テーブルに関連するデータファイルを新しいテーブル空間に移動することができます。 テーブルにインデックスがあっても移動されません。 インデックスを移動するには、別途SET TABLESPACEコマンドを実行します。 パーティションテーブルに適用された場合には何も移動されませんが、以後CREATE TABLE PARTITION OFで作られるパーティションは、TABLESPACE句により上書きされない限り、そのテーブル空間を使うようになります。

All tables in the current database in a tablespace can be moved by using the <literal>ALL IN TABLESPACE</literal> form, which will lock all tables to be moved first and then move each one. This form also supports <literal>OWNED BY</literal>, which will only move tables owned by the roles specified. If the <literal>NOWAIT</literal> option is specified then the command will fail if it is unable to acquire all of the locks required immediately. Note that system catalogs are not moved by this command; use <command>ALTER DATABASE</command> or explicit <command>ALTER TABLE</command> invocations instead if desired. The <literal>information_schema</literal> relations are not considered part of the system catalogs and will be moved. See also <link linkend="sql-createtablespace"><command>CREATE TABLESPACE</command></link>. ALL IN TABLESPACE構文を使うことで、テーブル空間内の現在のデータベースのすべてのテーブルを移動することができます。 この場合、移動されるすべてのテーブルがまずロックされ、それから一つずつ移動されます。 この構文はOWNED BYもサポートしており、これを使うと、指定のロールが所有しているテーブルだけを移動します。 NOWAITを指定した場合、必要とするすべてのロックを即座に獲得できなければ、このコマンドは失敗します。 このコマンドではシステムカタログは移動されないことに注意し、必要なら代わりにALTER DATABASEを使うか、あるいはALTER TABLEで明示的に指定してください。 information_schemaのリレーションはシステムカタログとはみなされないので、移動されます。 CREATE TABLESPACEも参照してください。

SET { LOGGED | UNLOGGED } #

This form changes the table from unlogged to logged or vice-versa (see <xref linkend="sql-createtable-unlogged"/>). It cannot be applied to a temporary table. この構文は、テーブルをログを取らないテーブルからログを取るテーブルに変更、あるいはその逆を行います(UNLOGGED参照)。 これは一時テーブルに対して使うことはできません。

This also changes the persistence of any sequences linked to the table (for identity or serial columns). However, it is also possible to change the persistence of such sequences separately. これは、テーブルにリンクされたシーケンス(ID列またはシリアル列)の永続性も変更します。 一方、このようなシーケンスの永続性を個別に変更することもできます。

SET ( storage_parameter [= value] [, ... ] ) #

This form changes one or more storage parameters for the table. See <xref linkend="sql-createtable-storage-parameters"/> in the <link linkend="sql-createtable"><command>CREATE TABLE</command></link> documentation for details on the available parameters. Note that the table contents will not be modified immediately by this command; depending on the parameter you might need to rewrite the table to get the desired effects. That can be done with <link linkend="sql-vacuum"><command>VACUUM FULL</command></link>, <link linkend="sql-cluster"><command>CLUSTER</command></link> or one of the forms of <command>ALTER TABLE</command> that forces a table rewrite. For planner related parameters, changes will take effect from the next time the table is locked so currently executing queries will not be affected. この構文は、1つ以上のテーブルの格納パラメータを変更します。 設定可能なパラメータの詳細に関してはCREATE TABLE文書の格納パラメータを参照してください。 このコマンドによってテーブルの内容が即座に変更されない点に注意してください。 パラメータによりますが、期待する効果を得るためにテーブルを書き換える必要がある場合があります。 このためには、VACUUM FULLCLUSTERまたはテーブルを強制的に書き換えるALTER TABLEの構文のいずれかを使用してください。 プランナに関連するパラメータについては、次にテーブルがロックされた時に変更が有効になるため、現在実行中の問い合わせは影響を受けません。

<literal>SHARE UPDATE EXCLUSIVE</literal> lock will be taken for fillfactor, toast and autovacuum storage parameters, as well as the planner parameter <varname>parallel_workers</varname>. fillfactor、TOAST、およびautovacuumのストレージパラメータおよびプランナに関連するパラメータparallel_workersについてはSHARE UPDATE EXCLUSIVEロックが獲得されます。

RESET ( storage_parameter [, ... ] ) #

This form resets one or more storage parameters to their defaults. As with <literal>SET</literal>, a table rewrite might be needed to update the table entirely. この構文は、1つ以上の格納パラメータをデフォルト値に再設定します。 SET同様、テーブル全体を更新するためにテーブルの書き換えが必要になる場合があります。

INHERIT parent_table #

This form adds the target table as a new child of the specified parent table. Subsequently, queries against the parent will include records of the target table. To be added as a child, the target table must already contain all the same columns as the parent (it could have additional columns, too). The columns must have matching data types, and if they have <literal>NOT NULL</literal> constraints in the parent then they must also have <literal>NOT NULL</literal> constraints in the child. この構文は、対象テーブルを指定した親テーブルの子テーブルとして追加します。 その後に行われる親テーブルへの問い合わせには対象テーブルの項目も含まれます。 子テーブルとして追加するためには、対象テーブルには親テーブルと同じ列がすべて含まれていなければなりません。 (この他の列を持つこともできます。) これらの列のデータ型は一致している必要があり、親テーブルでNOT NULL制約がある場合は、子テーブルでも同様にNOT NULL制約を持たなければなりません。

There must also be matching child-table constraints for all <literal>CHECK</literal> constraints of the parent, except those marked non-inheritable (that is, created with <literal>ALTER TABLE ... ADD CONSTRAINT ... NO INHERIT</literal>) in the parent, which are ignored; all child-table constraints matched must not be marked non-inheritable. Currently <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and <literal>FOREIGN KEY</literal> constraints are not considered, but this might change in the future. また、親テーブルのCHECK制約すべてについても、一致する制約が子テーブルに存在しなければなりません。 ただし、親テーブルにおいて継承不可と印付けされている(つまりALTER TABLE ... ADD CONSTRAINT ... NO INHERIT付きで作成された)制約は除きます(これらは無視されます)。 一致する子テーブルの制約はすべて継承不可であってはなりません。 現時点ではUNIQUEPRIMARY KEYFOREIGN KEY制約は無視されますが、将来変更されるかもしれません。

NO INHERIT parent_table #

This form removes the target table from the list of children of the specified parent table. Queries against the parent table will no longer include records drawn from the target table. この構文は、指定した親テーブルの子テーブル群から対象のテーブルを削除します。 親テーブルへの問い合わせでは、対象としたテーブルからのデータが含まれなくなります。

OF type_name #

This form links the table to a composite type as though <command>CREATE TABLE OF</command> had formed it. The table's list of column names and types must precisely match that of the composite type. The table must not inherit from any other table. These restrictions ensure that <command>CREATE TABLE OF</command> would permit an equivalent table definition. この構文は、CREATE TABLE OFで形成されたかのように、テーブルと複合型とを関連付けします。 テーブルの列名とその型のリストは、複合型のものと正確に一致していなければなりません。 テーブルはどのテーブルも継承していてはいけません。 これらの制限によりCREATE TABLE OFにより作成できるテーブル定義と同等になります。

NOT OF #

This form dissociates a typed table from its type. この構文は型と型付けされたテーブルの関連を取り除きます。

OWNER TO #

This form changes the owner of the table, sequence, view, materialized view, or foreign table to the specified user. この構文を使用すると、テーブル、シーケンス、ビュー、マテリアライズドビュー、または外部テーブルの所有者を、指定したユーザに変更できます。

REPLICA IDENTITY #

This form changes the information which is written to the write-ahead log to identify rows which are updated or deleted. In most cases, the old value of each column is only logged if it differs from the new value; however, if the old value is stored externally, it is always logged regardless of whether it changed. This option has no effect except when logical replication is in use. この形式は、先行書き込みログに書き込まれる情報を変更して、更新または削除された行を識別します。 ほとんどの場合、各列の古い値は、新しい値と異なる場合にのみログに記録されます。 ただし、古い値が外部に保存されている場合は、変更されたかどうかに関係なく、常にログに記録されます。 このオプションは、論理レプリケーションが使用されている場合を除いて何の効果もありません。

DEFAULT #

Records the old values of the columns of the primary key, if any. This is the default for non-system tables. 主キーの列に古い値がある場合、それを記録します。 これは、非システムテーブルのデフォルトです。

USING INDEX index_name #

Records the old values of the columns covered by the named index, that must be unique, not partial, not deferrable, and include only columns marked <literal>NOT NULL</literal>. If this index is dropped, the behavior is the same as <literal>NOTHING</literal>. 指定されたインデックスによってカバーされる列の古い値を記録します。 これは、一意であり、部分的ではなく、遅延可能でなく、NOT NULLとマークされた列のみを含む必要があります。 このインデックスが削除された場合、動作はNOTHINGと同じです。

FULL #

Records the old values of all columns in the row. 行のすべての列の古い値を記録します。

NOTHING #

Records no information about the old row. This is the default for system tables. 古い行に関する情報は記録されません。 これは、システムテーブルのデフォルトです。

RENAME #

The <literal>RENAME</literal> forms change the name of a table (or an index, sequence, view, materialized view, or foreign table), the name of an individual column in a table, or the name of a constraint of the table. When renaming a constraint that has an underlying index, the index is renamed as well. There is no effect on the stored data. RENAME構文を使用すると、テーブル(もしくは、インデックス、シーケンス、ビュー、マテリアライズドビュー、外部テーブル)の名前、テーブルの個々の列名、テーブルの制約名を変更できます。 元となるインデックスを持つ制約名を変更するとき、インデックス名も同様に変更されます。 格納されているデータへの影響はありません。

SET SCHEMA #

This form moves the table into another schema. Associated indexes, constraints, and sequences owned by table columns are moved as well. この構文を使用して、テーブルを別のスキーマに移動することができます。 関連するインデックスや制約、テーブル列により所有されるシーケンスも同様に移動されます。

ATTACH PARTITION partition_name { FOR VALUES partition_bound_spec | DEFAULT } #

This form attaches an existing table (which might itself be partitioned) as a partition of the target table. The table can be attached as a partition for specific values using <literal>FOR VALUES</literal> or as a default partition by using <literal>DEFAULT</literal>. For each index in the target table, a corresponding one will be created in the attached table; or, if an equivalent index already exists, it will be attached to the target table's index, as if <command>ALTER INDEX ATTACH PARTITION</command> had been executed. Note that if the existing table is a foreign table, it is currently not allowed to attach the table as a partition of the target table if there are <literal>UNIQUE</literal> indexes on the target table. (See also <xref linkend="sql-createforeigntable"/>.) For each user-defined row-level trigger that exists in the target table, a corresponding one is created in the attached table. この構文は、既存のテーブル(それ自体がパーティションテーブルのこともあります)を対象テーブルのパーティションとして追加します。 テーブルは、FOR VALUESを使って指定の値のパーティションとして、あるいは、DEFAULTを使ってデフォルトパーティションとして追加できます。 対象テーブルの各インデックスについて、対応するインデックスが付加されるテーブルに作られます。 また、同等のインデックスが既にある場合には、そのインデックスが、ALTER INDEX ATTACH PARTITIONが実行された場合と同様に、対象テーブルのインデックスに付加されます。 既存のテーブルが外部テーブルの場合、今のところ対象テーブルにUNIQUEインデックスがあるときにはテーブルを対象テーブルのパーティションとして追加することはできない点に注意してください(CREATE FOREIGN TABLEも参照してください)。 対象テーブルにある各ユーザ定義の行レベルのトリガに対しては、対応するものが付加されるテーブルに作られます。

A partition using <literal>FOR VALUES</literal> uses same syntax for <replaceable class="parameter">partition_bound_spec</replaceable> as <link linkend="sql-createtable"><command>CREATE TABLE</command></link>. The partition bound specification must correspond to the partitioning strategy and partition key of the target table. The table to be attached must have all the same columns as the target table and no more; moreover, the column types must also match. Also, it must have all the <literal>NOT NULL</literal> and <literal>CHECK</literal> constraints of the target table. Currently <literal>FOREIGN KEY</literal> constraints are not considered. <literal>UNIQUE</literal> and <literal>PRIMARY KEY</literal> constraints from the parent table will be created in the partition, if they don't already exist. If any of the <literal>CHECK</literal> constraints of the table being attached are marked <literal>NO INHERIT</literal>, the command will fail; such constraints must be recreated without the <literal>NO INHERIT</literal> clause. FOR VALUESを使ったパーティションはpartition_bound_specCREATE TABLEと同じ構文を使います。 パーティション境界の指定は、対象テーブルのパーティション戦略とパーティションキーと対応していなければなりません。 付加されるテーブルは、対象と全て同じ列を持ち、それ以上の列は持たず、列の型も一致していなければなりません。 また、対象テーブルにある全てのNOT NULLおよびCHECK制約を持たなければなりません。 今のところ、FOREIGN KEY制約は考慮されません。 親テーブルのUNIQUEおよびPRIMARY KEY制約は、既に在るのでなければ、パーティションに作られます。 もし、アタッチされるテーブルのいずれかのCHECK制約がNO INHERITと印付けされていたなら、コマンドは失敗します。 このような制約はNO INHERIT句なしに再作成しなければなりません。

If the new partition is a regular table, a full table scan is performed to check that existing rows in the table do not violate the partition constraint. It is possible to avoid this scan by adding a valid <literal>CHECK</literal> constraint to the table that allows only rows satisfying the desired partition constraint before running this command. The <literal>CHECK</literal> constraint will be used to determine that the table need not be scanned to validate the partition constraint. This does not work, however, if any of the partition keys is an expression and the partition does not accept <literal>NULL</literal> values. If attaching a list partition that will not accept <literal>NULL</literal> values, also add a <literal>NOT NULL</literal> constraint to the partition key column, unless it's an expression. 新しいパーティションが通常のテーブルの場合、テーブルに存在する行がパーティションの制約に違反しないことを確認するため、テーブルの全件走査が行われます。 このコマンドを実行するより前に、望まれるパーティションの制約を満たす行だけしか許さないような有効なCHECK制約をテーブルに追加すれば、この全件走査を避けることができます。 CHECK制約は、パーティションの制約を確認するためにテーブルをスキャンする必要がないか決めるために使われます。 しかし、パーティションキーに式が一つでもあり、パーティションがNULL値を受け付けないときは、この仕組みは機能しません。 NULL値を受け付けないリストパーティションに追加するときも、それが式でないなら、パーティションキーの列にNOT NULL制約を追加してください。

If the new partition is a foreign table, nothing is done to verify that all the rows in the foreign table obey the partition constraint. (See the discussion in <xref linkend="sql-createforeigntable"/> about constraints on the foreign table.) 新しいパーティションが外部テーブルの場合、外部テーブルのすべての行がパーティションの制約に従うかどうかの確認は何も行われません。 (外部テーブルの制約についてはCREATE FOREIGN TABLEの議論を参照してください。)

When a table has a default partition, defining a new partition changes the partition constraint for the default partition. The default partition can't contain any rows that would need to be moved to the new partition, and will be scanned to verify that none are present. This scan, like the scan of the new partition, can be avoided if an appropriate <literal>CHECK</literal> constraint is present. Also like the scan of the new partition, it is always skipped when the default partition is a foreign table. テーブルがデフォルトパーティションを持っている場合、新たなパーティションの定義はデフォルトパーティションに対するパーティション制約を変更します。 デフォルトパーティションは新パーティションに移動すべきいかなる行を含むことができず、そのような行が無いことを確認するためスキャンが行われます。 このスキャンは、新パーティションのスキャンと同様に、適切なCHECK制約があれば回避できます。 やはり、新パーティションのスキャンと同様に、デフォルトパーティションが外部テーブルであるときは、このスキャンは常に省略されます。

Attaching a partition acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock on the parent table, in addition to the <literal>ACCESS EXCLUSIVE</literal> locks on the table being attached and on the default partition (if any). パーティションの追加は、追加されるテーブルと(もしあれば)デフォルトパーティションでのACCESS EXCLUSIVEロックに加えて、親テーブルでSHARE UPDATE EXCLUSIVEロックを取得します。

Further locks must also be held on all sub-partitions if the table being attached is itself a partitioned table. Likewise if the default partition is itself a partitioned table. The locking of the sub-partitions can be avoided by adding a <literal>CHECK</literal> constraint as described in <xref linkend="ddl-partitioning-declarative-maintenance"/>. 追加されるテーブル自体がパーティションテーブルである場合は、すべてのサブパーティションでさらにロックを保持する必要があります。 デフォルトパーティション自体がパーティションテーブルである場合も同様です。 5.11.2.2で説明されているように、サブパーティションのロックはCHECK制約を追加することで回避できます。

DETACH PARTITION partition_name [ CONCURRENTLY | FINALIZE ] #

This form detaches the specified partition of the target table. The detached partition continues to exist as a standalone table, but no longer has any ties to the table from which it was detached. Any indexes that were attached to the target table's indexes are detached. Any triggers that were created as clones of those in the target table are removed. <literal>SHARE</literal> lock is obtained on any tables that reference this partitioned table in foreign key constraints. この構文は、指定したパーティションを対象のテーブルから切り離します。 切り離されたパーティションは単独のテーブルとして存在し続けますが、切り離される前のテーブルとの紐付けはなくなります。 対象テーブルのインデックスに付加されていた全てのインデックスも切り離されます。 対象テーブルのものの複製として作られたトリガは削除されます。 SHAREロックは、外部キー制約でこのパーティションテーブルを参照するすべてのテーブルで取得されます。

If <literal>CONCURRENTLY</literal> is specified, it runs using a reduced lock level to avoid blocking other sessions that might be accessing the partitioned table. In this mode, two transactions are used internally. During the first transaction, a <literal>SHARE UPDATE EXCLUSIVE</literal> lock is taken on both parent table and partition, and the partition is marked as undergoing detach; at that point, the transaction is committed and all other transactions using the partitioned table are waited for. Once all those transactions have completed, the second transaction acquires <literal>SHARE UPDATE EXCLUSIVE</literal> on the partitioned table and <literal>ACCESS EXCLUSIVE</literal> on the partition, and the detach process completes. A <literal>CHECK</literal> constraint that duplicates the partition constraint is added to the partition. <literal>CONCURRENTLY</literal> cannot be run in a transaction block and is not allowed if the partitioned table contains a default partition. CONCURRENTLYが指定されている場合、パーティションテーブルにアクセスしている可能性のある他のセッションをブロックしないように、ロックレベルを下げて実行します。 このモードでは、2つのトランザクションが内部で使用されます。 最初のトランザクションでは、SHARE UPDATE EXCLUSIVEロックが親テーブルとパーティションの両方で取得され、パーティションはデタッチ中としてマークされます。 その時点で、トランザクションはコミットされ、パーティションテーブルを使用する他のすべてのトランザクションは待機されます。 これらのトランザクションがすべて完了すると、2番目のトランザクションがパーティションテーブルのSHARE UPDATE EXCLUSIVEを取得し、パーティションでACCESS EXCLUSIVEを取得し、デタッチプロセスが完了します。 パーティション制約と重複するCHECK制約がパーティションに追加されます。 CONCURRENTLYはトランザクションブロック内で実行することはできず、パーティションテーブルにデフォルトパーティションが含まれる場合は許可されません。

If <literal>FINALIZE</literal> is specified, a previous <literal>DETACH CONCURRENTLY</literal> invocation that was canceled or interrupted is completed. At most one partition in a partitioned table can be pending detach at a time. FINALIZEが指定されている場合、キャンセルまたは中断された以前のDETACH CONCURRENTLYの呼び出しは完了します。 パーティションテーブル内で多くても1つのパーティションが一度にデタッチを保留できます。

All the forms of ALTER TABLE that act on a single table, except <literal>RENAME</literal>, <literal>SET SCHEMA</literal>, <literal>ATTACH PARTITION</literal>, and <literal>DETACH PARTITION</literal> can be combined into a list of multiple alterations to be applied together. For example, it is possible to add several columns and/or alter the type of several columns in a single command. This is particularly useful with large tables, since only one pass over the table need be made. RENAMESET SCHEMAATTACH PARTITIONDETACH PARTITIONは、複数の変更リストに結合して、まとめて処理することができますが、それらを除き、ALTER TABLEのすべての構文は1つだけのテーブルに対して作用します。 例えば、複数の列の追加、型の変更を単一のコマンドで実行することができます。 これは特に巨大なテーブルでは便利です。変更のために必要なテーブル全体の走査が1回で済むからです。

You must own the table to use <command>ALTER TABLE</command>. To change the schema or tablespace of a table, you must also have <literal>CREATE</literal> privilege on the new schema or tablespace. To add the table as a new child of a parent table, you must own the parent table as well. Also, to attach a table as a new partition of the table, you must own the table being attached. To alter the owner, you must be able to <literal>SET ROLE</literal> to the new owning role, and that role must have <literal>CREATE</literal> privilege on the table's schema. (These restrictions enforce that altering the owner doesn't do anything you couldn't do by dropping and recreating the table. However, a superuser can alter ownership of any table anyway.) To add a column or alter a column type or use the <literal>OF</literal> clause, you must also have <literal>USAGE</literal> privilege on the data type. ALTER TABLEコマンドを使用するには、変更するテーブルを所有している必要があります。 テーブルのスキーマあるいはテーブル空間を変更するには、新しいスキーマあるいはテーブル空間におけるCREATE権限も持っていなければなりません。 テーブルを親テーブルの新しい子テーブルとして追加するには、親テーブルも所有している必要があります。 またテーブルをテーブルのパーティションとして追加する場合、追加されるテーブルを所有している必要があります。 所有者を変更するには、新しい所有者ロールに対してSET ROLEができなければなりません。また、そのロールはテーブルのスキーマにおいてCREATE権限を持たなければなりません。 (この制限により、テーブルの削除と再作成を行ってもできないことが、所有者の変更によってもできないようにしています。 ただし、スーパーユーザはすべてのテーブルの所有者を変更することができます。) 列の追加、列の型の変更、OF句の使用を行うためには、データ型に対するUSAGE権限を持たなければなりません。

パラメータ

<title>Parameters</title>
IF EXISTS #

Do not throw an error if the table does not exist. A notice is issued in this case. テーブルが存在しない場合でもエラーとしません。 この場合は注意メッセージが発行されます。

name #

The name (optionally schema-qualified) of an existing table to alter. If <literal>ONLY</literal> is specified before the table name, only that table is altered. If <literal>ONLY</literal> is not specified, the table and all its descendant tables (if any) are altered. Optionally, <literal>*</literal> can be specified after the table name to explicitly indicate that descendant tables are included. 変更対象となる既存のテーブルの名前です(スキーマ修飾名も可)。 テーブル名の前にONLYが指定された場合、そのテーブルのみが変更されます。 ONLYが指定されていない場合、そのテーブルおよび(もしあれば)そのテーブルを継承する全てのテーブルが更新されます。 オプションで、テーブル名の後に*を指定することで、明示的に継承するテーブルも含まれることを示すことができます。

column_name #

Name of a new or existing column. 新規または既存の列の名前です。

new_column_name #

New name for an existing column. 既存の列の新しい名前です。

new_name #

New name for the table. テーブルの新しい名前です。

data_type #

Data type of the new column, or new data type for an existing column. 新しい列のデータ型、もしくは既存の列に対する新しいデータ型です。

table_constraint #

New table constraint for the table. テーブルの新しいテーブル制約です。

constraint_name #

Name of a new or existing constraint. 新しい、あるいは既存の制約の名前です。

CASCADE #

Automatically drop objects that depend on the dropped column or constraint (for example, views referencing the column), and in turn all objects that depend on those objects (see <xref linkend="ddl-depend"/>). 削除された列や制約に依存しているオブジェクト(例えば、削除された列を参照しているビューなど)を自動的に削除し、さらにそれらのオブジェクトに依存するすべてのオブジェクトも削除します(5.14参照)。

RESTRICT #

Refuse to drop the column or constraint if there are any dependent objects. This is the default behavior. 依存しているオブジェクトがある場合、列または制約の削除要求を拒否します。 これがデフォルトの動作です。

trigger_name #

Name of a single trigger to disable or enable. 有効または無効にする単一のトリガの名前です。

ALL #

Disable or enable all triggers belonging to the table. (This requires superuser privilege if any of the triggers are internally generated constraint triggers, such as those that are used to implement foreign key constraints or deferrable uniqueness and exclusion constraints.) テーブルに属するすべてのトリガを有効または無効にします。 (外部キー制約、遅延可能な一意性および排他制約を実装するために使用される、内部向けに生成される制約トリガが含まれる場合、スーパーユーザ権限が必要です。)

USER #

Disable or enable all triggers belonging to the table except for internally generated constraint triggers, such as those that are used to implement foreign key constraints or deferrable uniqueness and exclusion constraints. 外部キー制約、遅延可能な一意性および排他制約を実装するために使用される、内部向けに生成されるトリガを除く、テーブルに属するトリガすべてを有効または無効にします。

index_name #

The name of an existing index. 既存のインデックスの名前です。

storage_parameter #

The name of a table storage parameter. テーブルの格納パラメータの名前です。

value #

The new value for a table storage parameter. This might be a number or a word depending on the parameter. テーブルの格納パラメータの新しい値です。 パラメータによりこれは数値となることも文字列となることもあります。

parent_table #

A parent table to associate or de-associate with this table. このテーブルに関連付ける、または、このテーブルから関連付けを取り除く親テーブルです。

new_owner #

The user name of the new owner of the table. テーブルの新しい所有者のユーザ名です。

new_access_method #

The name of the access method to which the table will be converted. テーブルを変換する先のアクセスメソッドの名前です。

new_tablespace #

The name of the tablespace to which the table will be moved. テーブルを移動する先のテーブル空間の名前です。

new_schema #

The name of the schema to which the table will be moved. テーブルを移動する先のスキーマの名前です。

partition_name #

The name of the table to attach as a new partition or to detach from this table. 新しいパーティションとして追加する、またはテーブルから切り離すテーブルの名前です。

partition_bound_spec #

The partition bound specification for a new partition. Refer to <xref linkend="sql-createtable"/> for more details on the syntax of the same. 新しいパーティションのパーティション境界の指定です。 その構文の詳細についてはCREATE TABLEを参照してください。

<refsect1 id="sql-altertable-notes" xreflabel="Notes">

注釈

<title>Notes</title>

The key word <literal>COLUMN</literal> is noise and can be omitted. COLUMNキーワードには意味がなく、省略可能です。

When a column is added with <literal>ADD COLUMN</literal> and a non-volatile <literal>DEFAULT</literal> is specified, the default is evaluated at the time of the statement and the result stored in the table's metadata. That value will be used for the column for all existing rows. If no <literal>DEFAULT</literal> is specified, NULL is used. In neither case is a rewrite of the table required. ADD COLUMNで列が追加され、非変動性のDEFAULTが指定されたときには、デフォルトは宣言時に評価されてテーブルのメタデータに格納された結果です。 この値は全ての既存行の列に使われます。 DEFAULTが指定されなかった場合にはNULLが使われます。 どちらの場合もテーブルを書き直す必要はありません。

Adding a column with a volatile <literal>DEFAULT</literal> or changing the type of an existing column will require the entire table and its indexes to be rewritten. As an exception, when changing the type of an existing column, if the <literal>USING</literal> clause does not change the column contents and the old type is either binary coercible to the new type or an unconstrained domain over the new type, a table rewrite is not needed. However, indexes must always be rebuilt unless the system can verify that the new index would be logically equivalent to the existing one. For example, if the collation for a column has been changed, an index rebuild is always required because the new sort order might be different. However, in the absence of a collation change, a column can be changed from <type>text</type> to <type>varchar</type> (or vice versa) without rebuilding the indexes because these data types sort identically. Table and/or index rebuilds may take a significant amount of time for a large table; and will temporarily require as much as double the disk space. 変動性のDEFAULT句を持つ列を追加したり、既存の列の型を変更するには、テーブルとインデックス全体の書き換えが必要になります。 例外として、既存列の型を変更するとき、USING句が列の内容を変更せず、かつ、古い型が新しい型とバイナリ変換可能であるか新しい型全体に対する制約のないドメインである場合、テーブルの書き換えは必要ありません。 しかし、新しいインデックスが既存のものと論理的に等しいとシステムが確認できないのであれば、インデックスは常に再構築しなければなりません。 例えば、列の照合順序が変更された場合には、新しいソート順が異なるかもしれませんので、インデックスの再構築は常に必要です。 しかし、照合順序の変更がなければ、インデックスの再構築なしで列をtextからvarcharへ(またはその逆)と変更できます。データ型のソートが同一だからです。 テーブルが巨大な場合、テーブル、インデックスまたはその両方の再構築には非常に時間がかかる可能性があります。 また、一時的に2倍のディスク容量が必要とされます。

Adding a <literal>CHECK</literal> or <literal>NOT NULL</literal> constraint requires scanning the table to verify that existing rows meet the constraint, but does not require a table rewrite. CHECKあるいはNOT NULL制約を追加する時は、既存の行が制約に従うかどうかを検証するためにテーブルの走査が必要になりますが、テーブルの書き換えは必要ありません。

Similarly, when attaching a new partition it may be scanned to verify that existing rows meet the partition constraint. 同様に、新しいパーティションを追加するときは、既存の行がパーティションの制約を満たすかどうかを確認するため、テーブルが走査されるかもしれません。

The main reason for providing the option to specify multiple changes in a single <command>ALTER TABLE</command> is that multiple table scans or rewrites can thereby be combined into a single pass over the table. 単一のALTER TABLE内に複数の変更を指定できるオプションを提供する主な理由は、複数のテーブル走査や書き換えを1回のテーブル走査にまとめることができるようにすることです。

Scanning a large table to verify a new foreign key or check constraint can take a long time, and other updates to the table are locked out until the <command>ALTER TABLE ADD CONSTRAINT</command> command is committed. The main purpose of the <literal>NOT VALID</literal> constraint option is to reduce the impact of adding a constraint on concurrent updates. With <literal>NOT VALID</literal>, the <command>ADD CONSTRAINT</command> command does not scan the table and can be committed immediately. After that, a <literal>VALIDATE CONSTRAINT</literal> command can be issued to verify that existing rows satisfy the constraint. The validation step does not need to lock out concurrent updates, since it knows that other transactions will be enforcing the constraint for rows that they insert or update; only pre-existing rows need to be checked. Hence, validation acquires only a <literal>SHARE UPDATE EXCLUSIVE</literal> lock on the table being altered. (If the constraint is a foreign key then a <literal>ROW SHARE</literal> lock is also required on the table referenced by the constraint.) In addition to improving concurrency, it can be useful to use <literal>NOT VALID</literal> and <literal>VALIDATE CONSTRAINT</literal> in cases where the table is known to contain pre-existing violations. Once the constraint is in place, no new violations can be inserted, and the existing problems can be corrected at leisure until <literal>VALIDATE CONSTRAINT</literal> finally succeeds. 新しい外部キーや検査制約を検証するために大きなテーブルを走査するのは長い時間が掛かる可能性があり、ALTER TABLE ADD CONSTRAINTコマンドがコミットされるまで、そのテーブルのその他の更新は締め出されます。 NOT VALID制約オプションの主な目的は、同時実行中の更新に制約を追加する影響を減らすことです。 NOT VALIDを付ければ、ADD CONSTRAINTコマンドはテーブルを走査せず、すぐにコミットされます。 その後で、VALIDATE CONSTRAINTコマンドを発行して、既存の行が制約を満たすか検証できます。 他のトランザクションが挿入したり更新したりする行に対しては制約が強制されていることは分かっていますので、この検証操作では同時実行中の更新を締め出す必要はありません。既に存在する行だけ確認する必要があります。 それゆえ、検証には変更するテーブルのSHARE UPDATE EXCLUSIVEロックのみが必要です。 (制約が外部キーなら、制約が参照するテーブルのROW SHAREロックも必要です。) 同時実行性をさらに向上させるため、テーブルに既に制約違反が存在することを知っている場合にNOT VALIDVALIDATE CONSTRAINTを使うことは有用かもしれません。 一度制約が設定されれば、新しい違反は挿入されることはありませんし、既存の問題は、VALIDATE CONSTRAINTを最終的に成功するまで使って、余裕のある時に修正できます。

The <literal>DROP COLUMN</literal> form does not physically remove the column, but simply makes it invisible to SQL operations. Subsequent insert and update operations in the table will store a null value for the column. Thus, dropping a column is quick but it will not immediately reduce the on-disk size of your table, as the space occupied by the dropped column is not reclaimed. The space will be reclaimed over time as existing rows are updated. DROP COLUMN構文は、列を物理的には削除せず、SQLの操作に対して不可視にします。 このコマンドを実行した後、テーブルに挿入または更新が行われると、削除した列にはNULLが格納されます。 したがって、列の削除は短時間で行えます。 しかし、削除された列が占めていた領域がまだ回収されていないため、テーブルのディスク上のサイズはすぐには小さくなりません。 この領域は、その後既存の行が更新されるにつれて回収されます。

To force immediate reclamation of space occupied by a dropped column, you can execute one of the forms of <command>ALTER TABLE</command> that performs a rewrite of the whole table. This results in reconstructing each row with the dropped column replaced by a null value. 削除した列が占有していたスペースを即座に再利用できるようにするには、テーブル全体を書き換える構文のALTER TABLEを使用することができます。 この結果、各行の削除される列がNULL値で再構成されます。

The rewriting forms of <command>ALTER TABLE</command> are not MVCC-safe. After a table rewrite, the table will appear empty to concurrent transactions, if they are using a snapshot taken before the rewrite occurred. See <xref linkend="mvcc-caveats"/> for more details. テーブルを書き換える構文のALTER TABLEはMVCC的に安全ではありません。 同時実行中のトランザクションが、テーブル書き換えが発生する前に取得したスナップショットを使っている場合、テーブルの書き換え後はそのトランザクションにはテーブルが空であるように見えます。 詳しくは13.6を参照して下さい。

The <literal>USING</literal> option of <literal>SET DATA TYPE</literal> can actually specify any expression involving the old values of the row; that is, it can refer to other columns as well as the one being converted. This allows very general conversions to be done with the <literal>SET DATA TYPE</literal> syntax. Because of this flexibility, the <literal>USING</literal> expression is not applied to the column's default value (if any); the result might not be a constant expression as required for a default. This means that when there is no implicit or assignment cast from old to new type, <literal>SET DATA TYPE</literal> might fail to convert the default even though a <literal>USING</literal> clause is supplied. In such cases, drop the default with <literal>DROP DEFAULT</literal>, perform the <literal>ALTER TYPE</literal>, and then use <literal>SET DEFAULT</literal> to add a suitable new default. Similar considerations apply to indexes and constraints involving the column. SET DATA TYPEUSINGオプションでは、その行の古い値を含め、どのような式でも指定できます。 つまり、変換対象の列と同様に、その他の列も参照することができます。 そのため、一般的な変換をSET DATA TYPE構文で行うことができます。 この柔軟性のため、USING式は列のデフォルト値には(仮に存在していても)適用されません。 結果が定数式にならない可能性があるためです(デフォルト値は定数式でなければいけません)。 したがって、古い型から新しい型への暗黙キャストや代入キャストが存在しない場合、USINGが指定されていても、SET DATA TYPEがデフォルト値の変換に失敗する可能性があります。 この場合は、DROP DEFAULTでデフォルト値を削除し、ALTER TYPEを実行した後で、SET DEFAULTを使用して再度適切なデフォルト値を指定してください。 変更対象の列を含むインデックスと制約も同様の配慮が必要です。

If a table has any descendant tables, it is not permitted to add, rename, or change the type of a column in the parent table without doing the same to the descendants. This ensures that the descendants always have columns matching the parent. Similarly, a <literal>CHECK</literal> constraint cannot be renamed in the parent without also renaming it in all descendants, so that <literal>CHECK</literal> constraints also match between the parent and its descendants. (That restriction does not apply to index-based constraints, however.) Also, because selecting from the parent also selects from its descendants, a constraint on the parent cannot be marked valid unless it is also marked valid for those descendants. In all of these cases, <command>ALTER TABLE ONLY</command> will be rejected. そのテーブルを継承するテーブルがある場合、子テーブルに同じ処理を実行しなければ、親テーブルに対する列の追加、列の名前、列の型の変更を実行することはできません。 この制限により、子テーブルの列が常に親テーブルと一致していることが保証されます。 同様に、すべての子テーブルでCHECK制約の名前を変更し、それが親と子の間で一致するようにしなければ、親テーブルのCHECK制約の名前を変更することはできません。 (しかし、この制限はインデックスの基づく制約にはあらわれません。) また、親テーブルからSELECTすると、その子テーブルからもSELECTすることになるため、親テーブルの制約は、それが子テーブルでも有効であると印を付けられるまで、有効であると印を付けられません これらのすべての場合において、ALTER TABLE ONLYは受け付けられません。

A recursive <literal>DROP COLUMN</literal> operation will remove a descendant table's column only if the descendant does not inherit that column from any other parents and never had an independent definition of the column. A nonrecursive <literal>DROP COLUMN</literal> (i.e., <command>ALTER TABLE ONLY ... DROP COLUMN</command>) never removes any descendant columns, but instead marks them as independently defined rather than inherited. A nonrecursive <literal>DROP COLUMN</literal> command will fail for a partitioned table, because all partitions of a table must have the same columns as the partitioning root. 再帰的なDROP COLUMN操作では、子テーブルが他の親テーブルからその列を継承しておらず、かつ、その列について独立した定義を持っていない場合のみ、その子テーブルの列を削除します。 再帰的でないDROP COLUMN(つまり、ALTER TABLE ONLY ... DROP COLUMN)操作では、継承された列は削除されません。 削除する代わりに、その列は継承されておらず独立して定義されているという印を付けます。 再帰的でないDROP COLUMNコマンドは、パーティションテーブルでは失敗します。 テーブルのすべてのパーティションは、パーティションの最上位と同じ列を持っていなければならないからです。

The actions for identity columns (<literal>ADD GENERATED</literal>, <literal>SET</literal> etc., <literal>DROP IDENTITY</literal>), as well as the actions <literal>CLUSTER</literal>, <literal>OWNER</literal>, and <literal>TABLESPACE</literal> never recurse to descendant tables; that is, they always act as though <literal>ONLY</literal> were specified. Actions affecting trigger states recurse to partitions of partitioned tables (unless <literal>ONLY</literal> is specified), but never to traditional-inheritance descendants. Adding a constraint recurses only for <literal>CHECK</literal> constraints that are not marked <literal>NO INHERIT</literal>. IDENTITY列についての操作(ADD GENERATEDSETDROP IDENTITYなど)およびCLUSTEROWNERおよびTABLESPACEの操作は子テーブルに再帰的に伝わりません。 つまり、常にONLYが指定されているかのように動作します。 トリガの状態に影響を与える操作は、(ONLYが指定されていない限り)パーティション化されたテーブルのパーティションに再帰的に伝わりますが、従来の継承の子孫には再帰的に伝わりません。 制約の追加は、NO INHERIT印がないCHECK制約に関してのみ再帰的に伝わります。

Changing any part of a system catalog table is not permitted. システムカタログテーブルについては、いかなる部分の変更も許可されていません。

Refer to <xref linkend="sql-createtable"/> for a further description of valid parameters. <xref linkend="ddl"/> has further information on inheritance. 有効なパラメータの詳しい説明はCREATE TABLEを参照してください。 第5章に、継承に関するさらに詳しい情報があります。

<title>Examples</title>

To add a column of type <type>varchar</type> to a table: varchar型の列をテーブルに追加します。

ALTER TABLE distributors ADD COLUMN address varchar(30);

That will cause all existing rows in the table to be filled with null values for the new column. これは表の既存の行すべてで、新しい列をNULL値で埋めることになります。

To add a column with a non-null default: デフォルトが非NULLの列を追加します。

ALTER TABLE measurements
  ADD COLUMN mtime timestamp with time zone DEFAULT now();

Existing rows will be filled with the current time as the value of the new column, and then new rows will receive the time of their insertion. 既存の行では、新しい列の値として現在時刻が入ります。また、新しい行では挿入時刻を受け取ります。

To add a column and fill it with a value different from the default to be used later: 列を追加して、後で使われるデフォルトとは異なる値で埋めます。

ALTER TABLE transactions
  ADD COLUMN status varchar(30) DEFAULT 'old',
  ALTER COLUMN status SET default 'current';

Existing rows will be filled with <literal>old</literal>, but then the default for subsequent commands will be <literal>current</literal>. The effects are the same as if the two sub-commands had been issued in separate <command>ALTER TABLE</command> commands. 既存の行はoldで埋められますが、後続のコマンドに対するデフォルトはcurrentになります。 別々のALTER TABLEコマンドで2つの副コマンドを発行する場合と、効果は同じです。

To drop a column from a table: テーブルから列を削除します。

ALTER TABLE distributors DROP COLUMN address RESTRICT;

To change the types of two existing columns in one operation: 1つの操作で既存の2つの列の型を変更します。

ALTER TABLE distributors
    ALTER COLUMN address TYPE varchar(80),
    ALTER COLUMN name TYPE varchar(100);

To change an integer column containing Unix timestamps to <type>timestamp with time zone</type> via a <literal>USING</literal> clause: USING句を使用して、Unixタイムスタンプを持つinteger型の列をtimestamp with time zoneに変更します。

ALTER TABLE foo
    ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone
    USING
        timestamp with time zone 'epoch' + foo_timestamp * interval '1 second';

The same, when the column has a default expression that won't automatically cast to the new data type: 上と同じことをします。 ただし、その列は、自動的に新しいデータ型にキャストされないデフォルト式を持つ場合についてです。

ALTER TABLE foo
    ALTER COLUMN foo_timestamp DROP DEFAULT,
    ALTER COLUMN foo_timestamp TYPE timestamp with time zone
    USING
        timestamp with time zone 'epoch' + foo_timestamp * interval '1 second',
    ALTER COLUMN foo_timestamp SET DEFAULT now();

To rename an existing column: 既存の列の名前を変更します。

ALTER TABLE distributors RENAME COLUMN address TO city;

To rename an existing table: 既存のテーブルの名前を変更します。

ALTER TABLE distributors RENAME TO suppliers;

To rename an existing constraint: 既存の制約の名前を変更します。

ALTER TABLE distributors RENAME CONSTRAINT zipchk TO zip_check;

To add a not-null constraint to a column: 列に非NULL制約を付与します。

ALTER TABLE distributors ALTER COLUMN street SET NOT NULL;

To remove a not-null constraint from a column: 列から非NULL制約を削除します。

ALTER TABLE distributors ALTER COLUMN street DROP NOT NULL;

To add a check constraint to a table and all its children: テーブルとそのすべての子テーブルにCHECK制約を付与します。

ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5);

To add a check constraint only to a table and not to its children: そのテーブルのみに適用され、その子テーブルには適用されない検査制約を追加します。

ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT;

(The check constraint will not be inherited by future children, either.) (この検査制約はこの後作成される子テーブルにも継承されません。)

To remove a check constraint from a table and all its children: テーブルとそのすべての子テーブルからCHECK制約を削除します。

ALTER TABLE distributors DROP CONSTRAINT zipchk;

To remove a check constraint from one table only: 1つのテーブルのみから検査制約を削除します。

ALTER TABLE ONLY distributors DROP CONSTRAINT zipchk;

(The check constraint remains in place for any child tables.) (この検査制約はすべての子テーブルで残ったままです。)

To add a foreign key constraint to a table: テーブルに外部キー制約を付与します。

ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);

To add a foreign key constraint to a table with the least impact on other work: テーブルへの外部キーの追加で、他の作業への影響を最小限にするには、以下のようにします。

ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID;
ALTER TABLE distributors VALIDATE CONSTRAINT distfk;

To add a (multicolumn) unique constraint to a table: テーブルに(複数列の)一意性制約を付与します。

ALTER TABLE distributors ADD CONSTRAINT dist_id_zipcode_key UNIQUE (dist_id, zipcode);

To add an automatically named primary key constraint to a table, noting that a table can only ever have one primary key: 自動的に命名される主キー制約をテーブルに付与します。 1つのテーブルが持てる主キーは1つだけであることに注意してください。

ALTER TABLE distributors ADD PRIMARY KEY (dist_id);

To move a table to a different tablespace: テーブルを別のテーブル空間に移動します。

ALTER TABLE distributors SET TABLESPACE fasttablespace;

To move a table to a different schema: テーブルを別のスキーマに移動します。

ALTER TABLE myschema.distributors SET SCHEMA yourschema;

To recreate a primary key constraint, without blocking updates while the index is rebuilt: インデックスを再構築している間の更新をブロックすることなく、主キー制約を再作成します。

CREATE UNIQUE INDEX CONCURRENTLY dist_id_temp_idx ON distributors (dist_id);
ALTER TABLE distributors DROP CONSTRAINT distributors_pkey,
    ADD CONSTRAINT distributors_pkey PRIMARY KEY USING INDEX dist_id_temp_idx;

To attach a partition to a range-partitioned table: 範囲パーティションテーブルにパーティションを追加します。

ALTER TABLE measurement
    ATTACH PARTITION measurement_y2016m07 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');

To attach a partition to a list-partitioned table: リストパーティションテーブルにパーティションを追加します。

ALTER TABLE cities
    ATTACH PARTITION cities_ab FOR VALUES IN ('a', 'b');

To attach a partition to a hash-partitioned table: ハッシュパーティションテーブルにパーティションを追加します。

ALTER TABLE orders
    ATTACH PARTITION orders_p4 FOR VALUES WITH (MODULUS 4, REMAINDER 3);

To attach a default partition to a partitioned table: パーティションテーブルにデフォルトパーティションを追加します。

ALTER TABLE cities
    ATTACH PARTITION cities_partdef DEFAULT;

To detach a partition from a partitioned table: パーティションテーブルからパーティションを切り離します。

ALTER TABLE measurement
    DETACH PARTITION measurement_y2015m12;

互換性

<title>Compatibility</title>

The forms <literal>ADD</literal> (without <literal>USING INDEX</literal>), <literal>DROP [COLUMN]</literal>, <literal>DROP IDENTITY</literal>, <literal>RESTART</literal>, <literal>SET DEFAULT</literal>, <literal>SET DATA TYPE</literal> (without <literal>USING</literal>), <literal>SET GENERATED</literal>, and <literal>SET <replaceable>sequence_option</replaceable></literal> conform with the SQL standard. The other forms are <productname>PostgreSQL</productname> extensions of the SQL standard. Also, the ability to specify more than one manipulation in a single <command>ALTER TABLE</command> command is an extension. USING INDEXがない)ADDDROP [COLUMN]DROP IDENTITYRESTARTSET DEFAULT、(USINGのない)SET DATA TYPESET GENERATEDSET sequence_option構文は標準SQLに従います。 他の構文は標準SQLに対するPostgreSQLの拡張です。 また、単一のALTER TABLEコマンド内に複数の操作を指定する機能もPostgreSQLの拡張です。

<command>ALTER TABLE DROP COLUMN</command> can be used to drop the only column of a table, leaving a zero-column table. This is an extension of SQL, which disallows zero-column tables. ALTER TABLE DROP COLUMNを使って、1つしか列がないテーブルから列を削除して、列がないテーブルを作成することができます。 これはPostgreSQLの拡張です。SQLでは、列を持たないテーブルは認められていません。

関連項目

<title>See Also</title> CREATE TABLE