2 doc/src/sgml/ref/alter_table.sgml
3 PostgreSQL documentation
6 <refentry id="SQL-ALTERTABLE">
7 <indexterm zone="sql-altertable">
8 <primary>ALTER TABLE</primary>
12 <refentrytitle>ALTER TABLE</refentrytitle>
13 <manvolnum>7</manvolnum>
14 <refmiscinfo>SQL - Language Statements</refmiscinfo>
18 <refname>ALTER TABLE</refname>
19 <refpurpose>change the definition of a table</refpurpose>
24 ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="PARAMETER">name</replaceable> [ * ]
25 <replaceable class="PARAMETER">action</replaceable> [, ... ]
26 ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="PARAMETER">name</replaceable> [ * ]
27 RENAME [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> TO <replaceable class="PARAMETER">new_column_name</replaceable>
28 ALTER TABLE [ IF EXISTS ] [ ONLY ] <replaceable class="PARAMETER">name</replaceable> [ * ]
29 RENAME CONSTRAINT <replaceable class="PARAMETER">constraint_name</replaceable> TO <replaceable class="PARAMETER">new_constraint_name</replaceable>
30 ALTER TABLE [ IF EXISTS ] <replaceable class="PARAMETER">name</replaceable>
31 RENAME TO <replaceable class="PARAMETER">new_name</replaceable>
32 ALTER TABLE [ IF EXISTS ] <replaceable class="PARAMETER">name</replaceable>
33 SET SCHEMA <replaceable class="PARAMETER">new_schema</replaceable>
34 ALTER TABLE ALL IN TABLESPACE <replaceable class="PARAMETER">name</replaceable> [ OWNED BY <replaceable class="PARAMETER">role_name</replaceable> [, ... ] ]
35 SET TABLESPACE <replaceable class="PARAMETER">new_tablespace</replaceable> [ NOWAIT ]
36 ALTER TABLE [ IF EXISTS ] <replaceable class="PARAMETER">name</replaceable>
37 ATTACH PARTITION <replaceable class="PARAMETER">partition_name</replaceable> FOR VALUES <replaceable class="PARAMETER">partition_bound_spec</replaceable>
38 ALTER TABLE [ IF EXISTS ] <replaceable class="PARAMETER">name</replaceable>
39 DETACH PARTITION <replaceable class="PARAMETER">partition_name</replaceable>
41 <phrase>where <replaceable class="PARAMETER">action</replaceable> is one of:</phrase>
43 ADD [ COLUMN ] [ IF NOT EXISTS ] <replaceable class="PARAMETER">column_name</replaceable> <replaceable class="PARAMETER">data_type</replaceable> [ COLLATE <replaceable class="PARAMETER">collation</replaceable> ] [ <replaceable class="PARAMETER">column_constraint</replaceable> [ ... ] ]
44 DROP [ COLUMN ] [ IF EXISTS ] <replaceable class="PARAMETER">column_name</replaceable> [ RESTRICT | CASCADE ]
45 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> [ SET DATA ] TYPE <replaceable class="PARAMETER">data_type</replaceable> [ COLLATE <replaceable class="PARAMETER">collation</replaceable> ] [ USING <replaceable class="PARAMETER">expression</replaceable> ]
46 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> SET DEFAULT <replaceable class="PARAMETER">expression</replaceable>
47 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> DROP DEFAULT
48 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> { SET | DROP } NOT NULL
49 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( <replaceable>sequence_options</replaceable> ) ]
50 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> { SET GENERATED { ALWAYS | BY DEFAULT } | SET <replaceable>sequence_option</replaceable> | RESTART [ [ WITH ] <replaceable class="parameter">restart</replaceable> ] } [...]
51 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> DROP IDENTITY [ IF EXISTS ]
52 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> SET STATISTICS <replaceable class="PARAMETER">integer</replaceable>
53 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> SET ( <replaceable class="PARAMETER">attribute_option</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] )
54 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> RESET ( <replaceable class="PARAMETER">attribute_option</replaceable> [, ... ] )
55 ALTER [ COLUMN ] <replaceable class="PARAMETER">column_name</replaceable> SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }
56 ADD <replaceable class="PARAMETER">table_constraint</replaceable> [ NOT VALID ]
57 ADD <replaceable class="PARAMETER">table_constraint_using_index</replaceable>
58 ALTER CONSTRAINT <replaceable class="PARAMETER">constraint_name</replaceable> [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
59 VALIDATE CONSTRAINT <replaceable class="PARAMETER">constraint_name</replaceable>
60 DROP CONSTRAINT [ IF EXISTS ] <replaceable class="PARAMETER">constraint_name</replaceable> [ RESTRICT | CASCADE ]
61 DISABLE TRIGGER [ <replaceable class="PARAMETER">trigger_name</replaceable> | ALL | USER ]
62 ENABLE TRIGGER [ <replaceable class="PARAMETER">trigger_name</replaceable> | ALL | USER ]
63 ENABLE REPLICA TRIGGER <replaceable class="PARAMETER">trigger_name</replaceable>
64 ENABLE ALWAYS TRIGGER <replaceable class="PARAMETER">trigger_name</replaceable>
65 DISABLE RULE <replaceable class="PARAMETER">rewrite_rule_name</replaceable>
66 ENABLE RULE <replaceable class="PARAMETER">rewrite_rule_name</replaceable>
67 ENABLE REPLICA RULE <replaceable class="PARAMETER">rewrite_rule_name</replaceable>
68 ENABLE ALWAYS RULE <replaceable class="PARAMETER">rewrite_rule_name</replaceable>
69 DISABLE ROW LEVEL SECURITY
70 ENABLE ROW LEVEL SECURITY
71 FORCE ROW LEVEL SECURITY
72 NO FORCE ROW LEVEL SECURITY
73 CLUSTER ON <replaceable class="PARAMETER">index_name</replaceable>
77 SET TABLESPACE <replaceable class="PARAMETER">new_tablespace</replaceable>
78 SET { LOGGED | UNLOGGED }
79 SET ( <replaceable class="PARAMETER">storage_parameter</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] )
80 RESET ( <replaceable class="PARAMETER">storage_parameter</replaceable> [, ... ] )
81 INHERIT <replaceable class="PARAMETER">parent_table</replaceable>
82 NO INHERIT <replaceable class="PARAMETER">parent_table</replaceable>
83 OF <replaceable class="PARAMETER">type_name</replaceable>
85 OWNER TO { <replaceable class="PARAMETER">new_owner</replaceable> | CURRENT_USER | SESSION_USER }
86 REPLICA IDENTITY { DEFAULT | USING INDEX <replaceable class="PARAMETER">index_name</replaceable> | FULL | NOTHING }
88 <phrase>and <replaceable class="PARAMETER">table_constraint_using_index</replaceable> is:</phrase>
90 [ CONSTRAINT <replaceable class="PARAMETER">constraint_name</replaceable> ]
91 { UNIQUE | PRIMARY KEY } USING INDEX <replaceable class="PARAMETER">index_name</replaceable>
92 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
97 <title>Description</title>
100 <command>ALTER TABLE</command> changes the definition of an existing table.
101 There are several subforms described below. Note that the lock level required
102 may differ for each subform. An <literal>ACCESS EXCLUSIVE</literal> lock is held
103 unless explicitly noted. When multiple subcommands are listed, the lock
104 held will be the strictest one required from any subcommand.
108 <term><literal>ADD COLUMN [ IF NOT EXISTS ]</literal></term>
111 This form adds a new column to the table, using the same syntax as
112 <xref linkend="SQL-CREATETABLE">. If <literal>IF NOT EXISTS</literal>
113 is specified and a column already exists with this name,
120 <term><literal>DROP COLUMN [ IF EXISTS ]</literal></term>
123 This form drops a column from a table. Indexes and
124 table constraints involving the column will be automatically
126 Multivariate statistics referencing the dropped column will also be
127 removed if the removal of the column would cause the statistics to
128 contain data for only a single column.
129 You will need to say <literal>CASCADE</> if anything outside the table
130 depends on the column, for example, foreign key references or views.
131 If <literal>IF EXISTS</literal> is specified and the column
132 does not exist, no error is thrown. In this case a notice
139 <term><literal>SET DATA TYPE</literal></term>
142 This form changes the type of a column of a table. Indexes and
143 simple table constraints involving the column will be automatically
144 converted to use the new column type by reparsing the originally
146 The optional <literal>COLLATE</literal> clause specifies a collation
147 for the new column; if omitted, the collation is the default for the
149 The optional <literal>USING</literal>
150 clause specifies how to compute the new column value from the old;
151 if omitted, the default conversion is the same as an assignment
152 cast from old data type to new. A <literal>USING</literal>
153 clause must be provided if there is no implicit or assignment
154 cast from old to new type.
160 <term><literal>SET</literal>/<literal>DROP DEFAULT</literal></term>
163 These forms set or remove the default value for a column.
164 Default values only apply in subsequent <command>INSERT</command>
165 or <command>UPDATE</> commands; they do not cause rows already in the
172 <term><literal>SET</literal>/<literal>DROP NOT NULL</literal></term>
175 These forms change whether a column is marked to allow null
176 values or to reject null values. You can only use <literal>SET
177 NOT NULL</> when the column contains no null values.
181 If this table is a partition, one cannot perform <literal>DROP NOT NULL</literal>
182 on a column if it is marked <literal>NOT NULL</literal> in the parent
183 table. To drop the <literal>NOT NULL</literal> constraint from all the
184 partitions, perform <literal>DROP NOT NULL</literal> on the parent
185 table. Even if there is no <literal>NOT NULL</> constraint on the
186 parent, such a constraint can still be added to individual partitions,
187 if desired; that is, the children can disallow nulls even if the parent
188 allows them, but not the other way around.
194 <term><literal>ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY</literal></term>
195 <term><literal>SET GENERATED { ALWAYS | BY DEFAULT }</literal></term>
196 <term><literal>DROP IDENTITY [ IF EXISTS ]</literal></term>
199 These forms change whether a column is an identity column or change the
200 generation attribute of an existing identity column.
201 See <xref linkend="sql-createtable"> for details.
205 If <literal>DROP IDENTITY IF EXISTS</literal> is specified and the
206 column is not an identity column, no error is thrown. In this case a
207 notice is issued instead.
213 <term><literal>SET <replaceable>sequence_option</replaceable></literal></term>
214 <term><literal>RESTART</literal></term>
217 These forms alter the sequence that underlies an existing identity
218 column. <replaceable>sequence_option</replaceable> is an option
219 supported by <xref linkend="sql-altersequence"> such
220 as <literal>INCREMENT BY</literal>.
226 <term><literal>SET STATISTICS</literal></term>
230 sets the per-column statistics-gathering target for subsequent
231 <xref linkend="sql-analyze"> operations.
232 The target can be set in the range 0 to 10000; alternatively, set it
233 to -1 to revert to using the system default statistics
234 target (<xref linkend="guc-default-statistics-target">).
235 For more information on the use of statistics by the
236 <productname>PostgreSQL</productname> query planner, refer to
237 <xref linkend="planner-stats">.
240 <literal>SET STATISTICS</literal> acquires a
241 <literal>SHARE UPDATE EXCLUSIVE</literal> lock.
247 <term><literal>SET ( <replaceable class="PARAMETER">attribute_option</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] )</literal></term>
248 <term><literal>RESET ( <replaceable class="PARAMETER">attribute_option</replaceable> [, ... ] )</literal></term>
251 This form sets or resets per-attribute options. Currently, the only
252 defined per-attribute options are <literal>n_distinct</> and
253 <literal>n_distinct_inherited</>, which override the
254 number-of-distinct-values estimates made by subsequent
255 <xref linkend="sql-analyze">
256 operations. <literal>n_distinct</> affects the statistics for the table
257 itself, while <literal>n_distinct_inherited</> affects the statistics
258 gathered for the table plus its inheritance children. When set to a
259 positive value, <command>ANALYZE</> will assume that the column contains
260 exactly the specified number of distinct nonnull values. When set to a
261 negative value, which must be greater
262 than or equal to -1, <command>ANALYZE</> will assume that the number of
263 distinct nonnull values in the column is linear in the size of the
264 table; the exact count is to be computed by multiplying the estimated
265 table size by the absolute value of the given number. For example,
266 a value of -1 implies that all values in the column are distinct, while
267 a value of -0.5 implies that each value appears twice on the average.
268 This can be useful when the size of the table changes over time, since
269 the multiplication by the number of rows in the table is not performed
270 until query planning time. Specify a value of 0 to revert to estimating
271 the number of distinct values normally. For more information on the use
272 of statistics by the <productname>PostgreSQL</productname> query
273 planner, refer to <xref linkend="planner-stats">.
276 Changing per-attribute options acquires a
277 <literal>SHARE UPDATE EXCLUSIVE</literal> lock.
284 <literal>SET STORAGE</literal>
286 <primary>TOAST</primary>
287 <secondary>per-column storage settings</secondary>
292 This form sets the storage mode for a column. This controls whether this
293 column is held inline or in a secondary <acronym>TOAST</> table, and
295 should be compressed or not. <literal>PLAIN</literal> must be used
296 for fixed-length values such as <type>integer</type> and is
297 inline, uncompressed. <literal>MAIN</literal> is for inline,
298 compressible data. <literal>EXTERNAL</literal> is for external,
299 uncompressed data, and <literal>EXTENDED</literal> is for external,
300 compressed data. <literal>EXTENDED</literal> is the default for most
301 data types that support non-<literal>PLAIN</literal> storage.
302 Use of <literal>EXTERNAL</literal> will make substring operations on
303 very large <type>text</type> and <type>bytea</type> values run faster,
304 at the penalty of increased storage space. Note that
305 <literal>SET STORAGE</> doesn't itself change anything in the table,
306 it just sets the strategy to be pursued during future table updates.
307 See <xref linkend="storage-toast"> for more information.
313 <term><literal>ADD <replaceable class="PARAMETER">table_constraint</replaceable> [ NOT VALID ]</literal></term>
316 This form adds a new constraint to a table using the same syntax as
317 <xref linkend="SQL-CREATETABLE">, plus the option <literal>NOT
318 VALID</literal>, which is currently only allowed for foreign key
319 and CHECK constraints.
320 If the constraint is marked <literal>NOT VALID</literal>, the
321 potentially-lengthy initial check to verify that all rows in the table
322 satisfy the constraint is skipped. The constraint will still be
323 enforced against subsequent inserts or updates (that is, they'll fail
324 unless there is a matching row in the referenced table, in the case
325 of foreign keys; and they'll fail unless the new row matches the
326 specified check constraints). But the
327 database will not assume that the constraint holds for all rows in
328 the table, until it is validated by using the <literal>VALIDATE
329 CONSTRAINT</literal> option.
335 <term><literal>ADD <replaceable class="PARAMETER">table_constraint_using_index</replaceable></literal></term>
338 This form adds a new <literal>PRIMARY KEY</> or <literal>UNIQUE</>
339 constraint to a table based on an existing unique index. All the
340 columns of the index will be included in the constraint.
344 The index cannot have expression columns nor be a partial index.
345 Also, it must be a b-tree index with default sort ordering. These
346 restrictions ensure that the index is equivalent to one that would be
347 built by a regular <literal>ADD PRIMARY KEY</> or <literal>ADD UNIQUE</>
352 If <literal>PRIMARY KEY</> is specified, and the index's columns are not
353 already marked <literal>NOT NULL</>, then this command will attempt to
354 do <literal>ALTER COLUMN SET NOT NULL</> against each such column.
355 That requires a full table scan to verify the column(s) contain no
356 nulls. In all other cases, this is a fast operation.
360 If a constraint name is provided then the index will be renamed to match
361 the constraint name. Otherwise the constraint will be named the same as
366 After this command is executed, the index is <quote>owned</> by the
367 constraint, in the same way as if the index had been built by
368 a regular <literal>ADD PRIMARY KEY</> or <literal>ADD UNIQUE</>
369 command. In particular, dropping the constraint will make the index
375 Adding a constraint using an existing index can be helpful in
376 situations where a new constraint needs to be added without blocking
377 table updates for a long time. To do that, create the index using
378 <command>CREATE INDEX CONCURRENTLY</>, and then install it as an
379 official constraint using this syntax. See the example below.
386 <term><literal>ALTER CONSTRAINT</literal></term>
389 This form alters the attributes of a constraint that was previously
390 created. Currently only foreign key constraints may be altered.
396 <term><literal>VALIDATE CONSTRAINT</literal></term>
399 This form validates a foreign key or check constraint that was previously created
400 as <literal>NOT VALID</literal>, by scanning the table to ensure there
401 are no rows for which the constraint is not satisfied.
402 Nothing happens if the constraint is already marked valid.
405 Validation can be a long process on larger tables. The value of separating
406 validation from initial creation is that you can defer validation to less
407 busy times, or can be used to give additional time to correct pre-existing
408 errors while preventing new errors. Note also that validation on its own
409 does not prevent normal write commands against the table while it runs.
412 Validation acquires only a <literal>SHARE UPDATE EXCLUSIVE</literal> lock
413 on the table being altered. If the constraint is a foreign key then
414 a <literal>ROW SHARE</literal> lock is also required on
415 the table referenced by the constraint.
421 <term><literal>DROP CONSTRAINT [ IF EXISTS ]</literal></term>
424 This form drops the specified constraint on a table.
425 If <literal>IF EXISTS</literal> is specified and the constraint
426 does not exist, no error is thrown. In this case a notice is issued instead.
432 <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] TRIGGER</literal></term>
435 These forms configure the firing of trigger(s) belonging to the table.
436 A disabled trigger is still known to the system, but is not executed
437 when its triggering event occurs. For a deferred trigger, the enable
438 status is checked when the event occurs, not when the trigger function
439 is actually executed. One can disable or enable a single
440 trigger specified by name, or all triggers on the table, or only
441 user triggers (this option excludes internally generated constraint
442 triggers such as those that are used to implement foreign key
443 constraints or deferrable uniqueness and exclusion constraints).
444 Disabling or enabling internally generated constraint triggers
445 requires superuser privileges; it should be done with caution since
446 of course the integrity of the constraint cannot be guaranteed if the
447 triggers are not executed.
448 The trigger firing mechanism is also affected by the configuration
449 variable <xref linkend="guc-session-replication-role">. Simply enabled
450 triggers will fire when the replication role is <quote>origin</>
451 (the default) or <quote>local</>. Triggers configured as <literal>ENABLE
452 REPLICA</literal> will only fire if the session is in <quote>replica</>
453 mode, and triggers configured as <literal>ENABLE ALWAYS</literal> will
454 fire regardless of the current replication mode.
457 This command acquires a <literal>SHARE ROW EXCLUSIVE</literal> lock.
463 <term><literal>DISABLE</literal>/<literal>ENABLE [ REPLICA | ALWAYS ] RULE</literal></term>
466 These forms configure the firing of rewrite rules belonging to the table.
467 A disabled rule is still known to the system, but is not applied
468 during query rewriting. The semantics are as for disabled/enabled
469 triggers. This configuration is ignored for <literal>ON SELECT</literal> rules, which
470 are always applied in order to keep views working even if the current
471 session is in a non-default replication role.
477 <term><literal>DISABLE</literal>/<literal>ENABLE ROW LEVEL SECURITY</literal></term>
480 These forms control the application of row security policies belonging
481 to the table. If enabled and no policies exist for the table, then a
482 default-deny policy is applied. Note that policies can exist for a table
483 even if row level security is disabled - in this case, the policies will
484 NOT be applied and the policies will be ignored.
486 <xref linkend="SQL-CREATEPOLICY">.
492 <term><literal>NO FORCE</literal>/<literal>FORCE ROW LEVEL SECURITY</literal></term>
495 These forms control the application of row security policies belonging
496 to the table when the user is the table owner. If enabled, row level
497 security policies will be applied when the user is the table owner. If
498 disabled (the default) then row level security will not be applied when
499 the user is the table owner.
501 <xref linkend="SQL-CREATEPOLICY">.
507 <term><literal>CLUSTER ON</literal></term>
510 This form selects the default index for future
511 <xref linkend="SQL-CLUSTER">
512 operations. It does not actually re-cluster the table.
515 Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock.
521 <term><literal>SET WITHOUT CLUSTER</literal></term>
524 This form removes the most recently used
525 <xref linkend="SQL-CLUSTER">
526 index specification from the table. This affects
527 future cluster operations that don't specify an index.
530 Changing cluster options acquires a <literal>SHARE UPDATE EXCLUSIVE</literal> lock.
536 <term><literal>SET WITH OIDS</literal></term>
539 This form adds an <literal>oid</literal> system column to the
540 table (see <xref linkend="ddl-system-columns">).
541 It does nothing if the table already has OIDs.
545 Note that this is not equivalent to <literal>ADD COLUMN oid oid</>;
546 that would add a normal column that happened to be named
547 <literal>oid</>, not a system column.
553 <term><literal>SET WITHOUT OIDS</literal></term>
556 This form removes the <literal>oid</literal> system column from the
557 table. This is exactly equivalent to
558 <literal>DROP COLUMN oid RESTRICT</literal>,
559 except that it will not complain if there is already no
560 <literal>oid</literal> column.
566 <term><literal>SET TABLESPACE</literal></term>
569 This form changes the table's tablespace to the specified tablespace and
570 moves the data file(s) associated with the table to the new tablespace.
571 Indexes on the table, if any, are not moved; but they can be moved
572 separately with additional <literal>SET TABLESPACE</literal> commands.
573 All tables in the current database in a tablespace can be moved by using
574 the <literal>ALL IN TABLESPACE</literal> form, which will lock all tables
575 to be moved first and then move each one. This form also supports
576 <literal>OWNED BY</literal>, which will only move tables owned by the
577 roles specified. If the <literal>NOWAIT</literal> option is specified
578 then the command will fail if it is unable to acquire all of the locks
579 required immediately. Note that system catalogs are not moved by this
580 command, use <command>ALTER DATABASE</command> or explicit
581 <command>ALTER TABLE</command> invocations instead if desired. The
582 <literal>information_schema</literal> relations are not considered part
583 of the system catalogs and will be moved.
585 <xref linkend="SQL-CREATETABLESPACE">.
591 <term><literal>SET { LOGGED | UNLOGGED }</literal></term>
594 This form changes the table from unlogged to logged or vice-versa
595 (see <xref linkend="SQL-CREATETABLE-UNLOGGED">). It cannot be applied
596 to a temporary table.
602 <term><literal>SET ( <replaceable class="PARAMETER">storage_parameter</replaceable> = <replaceable class="PARAMETER">value</replaceable> [, ... ] )</literal></term>
605 This form changes one or more storage parameters for the table. See
606 <xref linkend="SQL-CREATETABLE-storage-parameters"
607 endterm="SQL-CREATETABLE-storage-parameters-title">
608 for details on the available parameters. Note that the table contents
609 will not be modified immediately by this command; depending on the
610 parameter you might need to rewrite the table to get the desired effects.
611 That can be done with <link linkend="SQL-VACUUM">VACUUM
612 FULL</>, <xref linkend="SQL-CLUSTER"> or one of the forms
613 of <command>ALTER TABLE</> that forces a table rewrite.
614 For planner related parameters, changes will take effect from the next
615 time the table is locked so currently executing queries will not be
620 <literal>SHARE UPDATE EXCLUSIVE</literal> lock will be taken for
621 fillfactor and autovacuum storage parameters, as well as the
622 following planner related parameters:
623 effective_io_concurrency, parallel_workers, seq_page_cost
624 random_page_cost, n_distinct and n_distinct_inherited.
629 While <command>CREATE TABLE</> allows <literal>OIDS</> to be specified
630 in the <literal>WITH (<replaceable
631 class="PARAMETER">storage_parameter</>)</literal> syntax,
632 <command>ALTER TABLE</> does not treat <literal>OIDS</> as a
633 storage parameter. Instead use the <literal>SET WITH OIDS</>
634 and <literal>SET WITHOUT OIDS</> forms to change OID status.
641 <term><literal>RESET ( <replaceable class="PARAMETER">storage_parameter</replaceable> [, ... ] )</literal></term>
644 This form resets one or more storage parameters to their
645 defaults. As with <literal>SET</>, a table rewrite might be
646 needed to update the table entirely.
652 <term><literal>INHERIT <replaceable class="PARAMETER">parent_table</replaceable></literal></term>
655 This form adds the target table as a new child of the specified parent
656 table. Subsequently, queries against the parent will include records
657 of the target table. To be added as a child, the target table must
658 already contain all the same columns as the parent (it could have
659 additional columns, too). The columns must have matching data types,
660 and if they have <literal>NOT NULL</literal> constraints in the parent
661 then they must also have <literal>NOT NULL</literal> constraints in the
666 There must also be matching child-table constraints for all
667 <literal>CHECK</literal> constraints of the parent, except those
668 marked non-inheritable (that is, created with <literal>ALTER TABLE ... ADD CONSTRAINT ... NO INHERIT</literal>)
669 in the parent, which are ignored; all child-table constraints matched
670 must not be marked non-inheritable.
672 <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and
673 <literal>FOREIGN KEY</literal> constraints are not considered, but
674 this might change in the future.
680 <term><literal>NO INHERIT <replaceable class="PARAMETER">parent_table</replaceable></literal></term>
683 This form removes the target table from the list of children of the
684 specified parent table.
685 Queries against the parent table will no longer include records drawn
686 from the target table.
692 <term><literal>OF <replaceable class="PARAMETER">type_name</replaceable></literal></term>
695 This form links the table to a composite type as though <command>CREATE
696 TABLE OF</> had formed it. The table's list of column names and types
697 must precisely match that of the composite type; the presence of
698 an <literal>oid</> system column is permitted to differ. The table must
699 not inherit from any other table. These restrictions ensure
700 that <command>CREATE TABLE OF</> would permit an equivalent table
707 <term><literal>NOT OF</literal></term>
710 This form dissociates a typed table from its type.
716 <term><literal>OWNER</literal></term>
719 This form changes the owner of the table, sequence, view, materialized view,
720 or foreign table to the specified user.
725 <varlistentry id="SQL-CREATETABLE-REPLICA-IDENTITY">
726 <term><literal>REPLICA IDENTITY</literal></term>
729 This form changes the information which is written to the write-ahead log
730 to identify rows which are updated or deleted. This option has no effect
731 except when logical replication is in use. <literal>DEFAULT</>
732 (the default for non-system tables) records the
733 old values of the columns of the primary key, if any. <literal>USING INDEX</>
734 records the old values of the columns covered by the named index, which
735 must be unique, not partial, not deferrable, and include only columns marked
736 <literal>NOT NULL</>. <literal>FULL</> records the old values of all columns
737 in the row. <literal>NOTHING</> records no information about the old row.
738 (This is the default for system tables.)
739 In all cases, no old values are logged unless at least one of the columns
740 that would be logged differs between the old and new versions of the row.
746 <term><literal>RENAME</literal></term>
749 The <literal>RENAME</literal> forms change the name of a table
750 (or an index, sequence, view, materialized view, or foreign table), the name
751 of an individual column in a table, or the name of a constraint of the table.
752 There is no effect on the stored data.
758 <term><literal>SET SCHEMA</literal></term>
761 This form moves the table into another schema. Associated indexes,
762 constraints, and sequences owned by table columns are moved as well.
768 <term><literal>ATTACH PARTITION <replaceable class="PARAMETER">partition_name</replaceable> FOR VALUES <replaceable class="PARAMETER">partition_bound_spec</replaceable></literal></term>
771 This form attaches an existing table (which might itself be partitioned)
772 as a partition of the target table using the same syntax for
773 <replaceable class="PARAMETER">partition_bound_spec</replaceable> as
774 <xref linkend="sql-createtable">. The partition bound specification
775 must correspond to the partitioning strategy and partition key of the
776 target table. The table to be attached must have all the same columns
777 as the target table and no more; moreover, the column types must also
778 match. Also, it must have all the <literal>NOT NULL</literal> and
779 <literal>CHECK</literal> constraints of the target table. Currently
780 <literal>UNIQUE</literal>, <literal>PRIMARY KEY</literal>, and
781 <literal>FOREIGN KEY</literal> constraints are not considered.
782 If any of the <literal>CHECK</literal> constraints of the table being
783 attached is marked <literal>NO INHERIT</literal>, the command will fail;
784 such a constraint must be recreated without the <literal>NO INHERIT</literal>
789 If the new partition is a regular table, a full table scan is performed
790 to check that no existing row in the table violates the partition
791 constraint. It is possible to avoid this scan by adding a valid
792 <literal>CHECK</literal> constraint to the table that would allow only
793 the rows satisfying the desired partition constraint before running this
794 command. It will be determined using such a constraint that the table
795 need not be scanned to validate the partition constraint. This does not
796 work, however, if any of the partition keys is an expression and the
797 partition does not accept <literal>NULL</literal> values. If attaching
798 a list partition that will not accept <literal>NULL</literal> values,
799 also add <literal>NOT NULL</literal> constraint to the partition key
800 column, unless it's an expression.
804 If the new partition is a foreign table, nothing is done to verify
805 that all the rows in the foreign table obey the partition constraint.
806 (See the discussion in <xref linkend="SQL-CREATEFOREIGNTABLE"> about
807 constraints on the foreign table.)
813 <term><literal>DETACH PARTITION</literal> <replaceable class="PARAMETER">partition_name</replaceable></term>
816 This form detaches specified partition of the target table. The detached
817 partition continues to exist as a standalone table, but no longer has any
818 ties to the table from which it was detached.
827 All the forms of ALTER TABLE that act on a single table, except
828 <literal>RENAME</literal>, <literal>SET SCHEMA</literal>,
829 <literal>ATTACH PARTITION</literal>, and
830 <literal>DETACH PARTITION</literal> can be combined into
831 a list of multiple alterations to be applied together. For example, it
832 is possible to add several columns and/or alter the type of several
833 columns in a single command. This is particularly useful with large
834 tables, since only one pass over the table need be made.
838 You must own the table to use <command>ALTER TABLE</>.
839 To change the schema or tablespace of a table, you must also have
840 <literal>CREATE</literal> privilege on the new schema or tablespace.
841 To add the table as a new child of a parent table, you must own the parent
842 table as well. Also, to attach a table as a new partition of the table,
843 you must own the table being attached.
844 To alter the owner, you must also be a direct or indirect member of the new
845 owning role, and that role must have <literal>CREATE</literal> privilege on
846 the table's schema. (These restrictions enforce that altering the owner
847 doesn't do anything you couldn't do by dropping and recreating the table.
848 However, a superuser can alter ownership of any table anyway.)
849 To add a column or alter a column type or use the <literal>OF</literal>
850 clause, you must also have <literal>USAGE</literal> privilege on the data
856 <title>Parameters</title>
861 <term><literal>IF EXISTS</literal></term>
864 Do not throw an error if the table does not exist. A notice is issued
871 <term><replaceable class="PARAMETER">name</replaceable></term>
874 The name (optionally schema-qualified) of an existing table to
875 alter. If <literal>ONLY</> is specified before the table name, only
876 that table is altered. If <literal>ONLY</> is not specified, the table
877 and all its descendant tables (if any) are altered. Optionally,
878 <literal>*</> can be specified after the table name to explicitly
879 indicate that descendant tables are included.
885 <term><replaceable class="PARAMETER">column_name</replaceable></term>
888 Name of a new or existing column.
894 <term><replaceable class="PARAMETER">new_column_name</replaceable></term>
897 New name for an existing column.
903 <term><replaceable class="PARAMETER">new_name</replaceable></term>
906 New name for the table.
912 <term><replaceable class="PARAMETER">data_type</replaceable></term>
915 Data type of the new column, or new data type for an existing
922 <term><replaceable class="PARAMETER">table_constraint</replaceable></term>
925 New table constraint for the table.
931 <term><replaceable class="PARAMETER">constraint_name</replaceable></term>
934 Name of a new or existing constraint.
940 <term><literal>CASCADE</literal></term>
943 Automatically drop objects that depend on the dropped column
944 or constraint (for example, views referencing the column),
945 and in turn all objects that depend on those objects
946 (see <xref linkend="ddl-depend">).
952 <term><literal>RESTRICT</literal></term>
955 Refuse to drop the column or constraint if there are any dependent
956 objects. This is the default behavior.
962 <term><replaceable class="PARAMETER">trigger_name</replaceable></term>
965 Name of a single trigger to disable or enable.
971 <term><literal>ALL</literal></term>
974 Disable or enable all triggers belonging to the table.
975 (This requires superuser privilege if any of the triggers are
976 internally generated constraint triggers such as those that are used
977 to implement foreign key constraints or deferrable uniqueness and
978 exclusion constraints.)
984 <term><literal>USER</literal></term>
987 Disable or enable all triggers belonging to the table except for
988 internally generated constraint triggers such as those that are used
989 to implement foreign key constraints or deferrable uniqueness and
990 exclusion constraints.
996 <term><replaceable class="PARAMETER">index_name</replaceable></term>
999 The name of an existing index.
1005 <term><replaceable class="PARAMETER">storage_parameter</replaceable></term>
1008 The name of a table storage parameter.
1014 <term><replaceable class="PARAMETER">value</replaceable></term>
1017 The new value for a table storage parameter.
1018 This might be a number or a word depending on the parameter.
1024 <term><replaceable class="PARAMETER">parent_table</replaceable></term>
1027 A parent table to associate or de-associate with this table.
1033 <term><replaceable class="PARAMETER">new_owner</replaceable></term>
1036 The user name of the new owner of the table.
1042 <term><replaceable class="PARAMETER">new_tablespace</replaceable></term>
1045 The name of the tablespace to which the table will be moved.
1051 <term><replaceable class="PARAMETER">new_schema</replaceable></term>
1054 The name of the schema to which the table will be moved.
1060 <term><replaceable class="PARAMETER">partition_name</replaceable></term>
1063 The name of the table to attach as a new partition or to detach from this table.
1069 <term><replaceable class="PARAMETER">partition_bound_spec</replaceable></term>
1072 The partition bound specification for a new partition. Refer to
1073 <xref linkend="sql-createtable"> for more details on the syntax of the same.
1082 <title>Notes</title>
1085 The key word <literal>COLUMN</literal> is noise and can be omitted.
1089 When a column is added with <literal>ADD COLUMN</literal>, all existing
1090 rows in the table are initialized with the column's default value
1091 (NULL if no <literal>DEFAULT</> clause is specified).
1092 If there is no <literal>DEFAULT</> clause, this is merely a metadata
1093 change and does not require any immediate update of the table's data;
1094 the added NULL values are supplied on readout, instead.
1098 Adding a column with a <literal>DEFAULT</> clause or changing the type of
1099 an existing column will require the entire table and its indexes to be
1100 rewritten. As an exception when changing the type of an existing column,
1101 if the <literal>USING</> clause does not change the column
1102 contents and the old type is either binary coercible to the new type or
1103 an unconstrained domain over the new type, a table rewrite is not needed;
1104 but any indexes on the affected columns must still be rebuilt. Adding or
1105 removing a system <literal>oid</> column also requires rewriting the entire
1106 table. Table and/or index rebuilds may take a significant amount of time
1107 for a large table; and will temporarily require as much as double the disk
1112 Adding a <literal>CHECK</> or <literal>NOT NULL</> constraint requires
1113 scanning the table to verify that existing rows meet the constraint,
1114 but does not require a table rewrite.
1118 Similarly, when attaching a new partition it may be scanned to verify that
1119 existing rows meet the partition constraint.
1123 The main reason for providing the option to specify multiple changes
1124 in a single <command>ALTER TABLE</> is that multiple table scans or
1125 rewrites can thereby be combined into a single pass over the table.
1129 The <literal>DROP COLUMN</literal> form does not physically remove
1130 the column, but simply makes it invisible to SQL operations. Subsequent
1131 insert and update operations in the table will store a null value for the
1132 column. Thus, dropping a column is quick but it will not immediately
1133 reduce the on-disk size of your table, as the space occupied
1134 by the dropped column is not reclaimed. The space will be
1135 reclaimed over time as existing rows are updated. (These statements do
1136 not apply when dropping the system <literal>oid</> column; that is done
1137 with an immediate rewrite.)
1141 To force immediate reclamation of space occupied by a dropped column,
1142 you can execute one of the forms of <command>ALTER TABLE</> that
1143 performs a rewrite of the whole table. This results in reconstructing
1144 each row with the dropped column replaced by a null value.
1148 The rewriting forms of <command>ALTER TABLE</> are not MVCC-safe.
1149 After a table rewrite, the table will appear empty to concurrent
1150 transactions, if they are using a snapshot taken before the rewrite
1151 occurred. See <xref linkend="mvcc-caveats"> for more details.
1155 The <literal>USING</literal> option of <literal>SET DATA TYPE</> can actually
1156 specify any expression involving the old values of the row; that is, it
1157 can refer to other columns as well as the one being converted. This allows
1158 very general conversions to be done with the <literal>SET DATA TYPE</>
1159 syntax. Because of this flexibility, the <literal>USING</literal>
1160 expression is not applied to the column's default value (if any); the
1161 result might not be a constant expression as required for a default.
1162 This means that when there is no implicit or assignment cast from old to
1163 new type, <literal>SET DATA TYPE</> might fail to convert the default even
1164 though a <literal>USING</literal> clause is supplied. In such cases,
1165 drop the default with <literal>DROP DEFAULT</>, perform the <literal>ALTER
1166 TYPE</>, and then use <literal>SET DEFAULT</> to add a suitable new
1167 default. Similar considerations apply to indexes and constraints involving
1172 If a table has any descendant tables, it is not permitted to add,
1173 rename, or change the type of a column in the parent table without doing
1174 same to the descendants. This ensures that the descendants always have
1175 columns matching the parent. Similarly, a constraint cannot be renamed
1176 in the parent without also renaming it in all descendants, so that
1177 constraints also match between the parent and its descendants.
1178 Also, because selecting from the parent also selects from its descendants,
1179 a constraint on the parent cannot be marked valid unless it is also marked
1180 valid for those descendants. In all of these cases, <command>ALTER TABLE
1181 ONLY</command> will be rejected.
1185 A recursive <literal>DROP COLUMN</literal> operation will remove a
1186 descendant table's column only if the descendant does not inherit
1187 that column from any other parents and never had an independent
1188 definition of the column. A nonrecursive <literal>DROP
1189 COLUMN</literal> (i.e., <command>ALTER TABLE ONLY ... DROP
1190 COLUMN</command>) never removes any descendant columns, but
1191 instead marks them as independently defined rather than inherited.
1192 A nonrecursive <literal>DROP COLUMN</literal> command will fail for a
1193 partitioned table, because all partitions of a table must have the same
1194 columns as the partitioning root.
1198 The actions for identity columns (<literal>ADD
1199 GENERATED</literal>, <literal>SET</literal> etc., <literal>DROP
1200 IDENTITY</literal>), as well as the actions
1201 <literal>TRIGGER</>, <literal>CLUSTER</>, <literal>OWNER</>,
1202 and <literal>TABLESPACE</> never recurse to descendant tables;
1203 that is, they always act as though <literal>ONLY</> were specified.
1204 Adding a constraint recurses only for <literal>CHECK</> constraints
1205 that are not marked <literal>NO INHERIT</>.
1209 Changing any part of a system catalog table is not permitted.
1213 Refer to <xref linkend="sql-createtable"> for a further description of valid
1214 parameters. <xref linkend="ddl"> has further information on
1220 <title>Examples</title>
1223 To add a column of type <type>varchar</type> to a table:
1225 ALTER TABLE distributors ADD COLUMN address varchar(30);
1230 To drop a column from a table:
1232 ALTER TABLE distributors DROP COLUMN address RESTRICT;
1237 To change the types of two existing columns in one operation:
1239 ALTER TABLE distributors
1240 ALTER COLUMN address TYPE varchar(80),
1241 ALTER COLUMN name TYPE varchar(100);
1246 To change an integer column containing Unix timestamps to <type>timestamp
1247 with time zone</type> via a <literal>USING</literal> clause:
1250 ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone
1252 timestamp with time zone 'epoch' + foo_timestamp * interval '1 second';
1257 The same, when the column has a default expression that won't automatically
1258 cast to the new data type:
1261 ALTER COLUMN foo_timestamp DROP DEFAULT,
1262 ALTER COLUMN foo_timestamp TYPE timestamp with time zone
1264 timestamp with time zone 'epoch' + foo_timestamp * interval '1 second',
1265 ALTER COLUMN foo_timestamp SET DEFAULT now();
1270 To rename an existing column:
1272 ALTER TABLE distributors RENAME COLUMN address TO city;
1277 To rename an existing table:
1279 ALTER TABLE distributors RENAME TO suppliers;
1284 To rename an existing constraint:
1286 ALTER TABLE distributors RENAME CONSTRAINT zipchk TO zip_check;
1291 To add a not-null constraint to a column:
1293 ALTER TABLE distributors ALTER COLUMN street SET NOT NULL;
1295 To remove a not-null constraint from a column:
1297 ALTER TABLE distributors ALTER COLUMN street DROP NOT NULL;
1302 To add a check constraint to a table and all its children:
1304 ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5);
1309 To add a check constraint only to a table and not to its children:
1311 ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT;
1313 (The check constraint will not be inherited by future children, either.)
1317 To remove a check constraint from a table and all its children:
1319 ALTER TABLE distributors DROP CONSTRAINT zipchk;
1324 To remove a check constraint from one table only:
1326 ALTER TABLE ONLY distributors DROP CONSTRAINT zipchk;
1328 (The check constraint remains in place for any child tables.)
1332 To add a foreign key constraint to a table:
1334 ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);
1339 To add a foreign key constraint to a table with the least impact on other work:
1341 ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID;
1342 ALTER TABLE distributors VALIDATE CONSTRAINT distfk;
1347 To add a (multicolumn) unique constraint to a table:
1349 ALTER TABLE distributors ADD CONSTRAINT dist_id_zipcode_key UNIQUE (dist_id, zipcode);
1354 To add an automatically named primary key constraint to a table, noting
1355 that a table can only ever have one primary key:
1357 ALTER TABLE distributors ADD PRIMARY KEY (dist_id);
1362 To move a table to a different tablespace:
1364 ALTER TABLE distributors SET TABLESPACE fasttablespace;
1369 To move a table to a different schema:
1371 ALTER TABLE myschema.distributors SET SCHEMA yourschema;
1376 To recreate a primary key constraint, without blocking updates while the
1379 CREATE UNIQUE INDEX CONCURRENTLY dist_id_temp_idx ON distributors (dist_id);
1380 ALTER TABLE distributors DROP CONSTRAINT distributors_pkey,
1381 ADD CONSTRAINT distributors_pkey PRIMARY KEY USING INDEX dist_id_temp_idx;
1382 </programlisting></para>
1385 Attach a partition to range partitioned table:
1387 ALTER TABLE measurement
1388 ATTACH PARTITION measurement_y2016m07 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');
1389 </programlisting></para>
1392 Attach a partition to list partitioned table:
1395 ATTACH PARTITION cities_ab FOR VALUES IN ('a', 'b');
1396 </programlisting></para>
1399 Detach a partition from partitioned table:
1401 ALTER TABLE measurement
1402 DETACH PARTITION measurement_y2015m12;
1403 </programlisting></para>
1408 <title>Compatibility</title>
1411 The forms <literal>ADD</literal> (without <literal>USING INDEX</literal>),
1412 <literal>DROP [COLUMN]</>, <literal>DROP IDENTITY</literal>, <literal>RESTART</literal>,
1413 <literal>SET DEFAULT</>, <literal>SET DATA TYPE</literal> (without <literal>USING</literal>),
1414 <literal>SET GENERATED</literal>, and <literal>SET <replaceable>sequence_option</replaceable></literal>
1415 conform with the SQL standard. The other forms are
1416 <productname>PostgreSQL</productname> extensions of the SQL standard.
1417 Also, the ability to specify more than one manipulation in a single
1418 <command>ALTER TABLE</> command is an extension.
1422 <command>ALTER TABLE DROP COLUMN</> can be used to drop the only
1423 column of a table, leaving a zero-column table. This is an
1424 extension of SQL, which disallows zero-column tables.
1429 <title>See Also</title>
1431 <simplelist type="inline">
1432 <member><xref linkend="sql-createtable"></member>