]> begriffs open source - ai-pg/blob - full-docs/man7/ALTER_TABLE.7
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / man7 / ALTER_TABLE.7
1 '\" t
2 .\"     Title: ALTER TABLE
3 .\"    Author: The PostgreSQL Global Development Group
4 .\" Generator: DocBook XSL Stylesheets vsnapshot <http://docbook.sf.net/>
5 .\"      Date: 2025
6 .\"    Manual: PostgreSQL 18.0 Documentation
7 .\"    Source: PostgreSQL 18.0
8 .\"  Language: English
9 .\"
10 .TH "ALTER TABLE" "7" "2025" "PostgreSQL 18.0" "PostgreSQL 18.0 Documentation"
11 .\" -----------------------------------------------------------------
12 .\" * Define some portability stuff
13 .\" -----------------------------------------------------------------
14 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 .\" http://bugs.debian.org/507673
16 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17 .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 .ie \n(.g .ds Aq \(aq
19 .el       .ds Aq '
20 .\" -----------------------------------------------------------------
21 .\" * set default formatting
22 .\" -----------------------------------------------------------------
23 .\" disable hyphenation
24 .nh
25 .\" disable justification (adjust text to left margin only)
26 .ad l
27 .\" -----------------------------------------------------------------
28 .\" * MAIN CONTENT STARTS HERE *
29 .\" -----------------------------------------------------------------
30 .SH "NAME"
31 ALTER_TABLE \- change the definition of a table
32 .SH "SYNOPSIS"
33 .sp
34 .nf
35 ALTER TABLE [ IF EXISTS ] [ ONLY ] \fIname\fR [ * ]
36     \fIaction\fR [, \&.\&.\&. ]
37 ALTER TABLE [ IF EXISTS ] [ ONLY ] \fIname\fR [ * ]
38     RENAME [ COLUMN ] \fIcolumn_name\fR TO \fInew_column_name\fR
39 ALTER TABLE [ IF EXISTS ] [ ONLY ] \fIname\fR [ * ]
40     RENAME CONSTRAINT \fIconstraint_name\fR TO \fInew_constraint_name\fR
41 ALTER TABLE [ IF EXISTS ] \fIname\fR
42     RENAME TO \fInew_name\fR
43 ALTER TABLE [ IF EXISTS ] \fIname\fR
44     SET SCHEMA \fInew_schema\fR
45 ALTER TABLE ALL IN TABLESPACE \fIname\fR [ OWNED BY \fIrole_name\fR [, \&.\&.\&. ] ]
46     SET TABLESPACE \fInew_tablespace\fR [ NOWAIT ]
47 ALTER TABLE [ IF EXISTS ] \fIname\fR
48     ATTACH PARTITION \fIpartition_name\fR { FOR VALUES \fIpartition_bound_spec\fR | DEFAULT }
49 ALTER TABLE [ IF EXISTS ] \fIname\fR
50     DETACH PARTITION \fIpartition_name\fR [ CONCURRENTLY | FINALIZE ]
51
52 where \fIaction\fR is one of:
53
54     ADD [ COLUMN ] [ IF NOT EXISTS ] \fIcolumn_name\fR \fIdata_type\fR [ COLLATE \fIcollation\fR ] [ \fIcolumn_constraint\fR [ \&.\&.\&. ] ]
55     DROP [ COLUMN ] [ IF EXISTS ] \fIcolumn_name\fR [ RESTRICT | CASCADE ]
56     ALTER [ COLUMN ] \fIcolumn_name\fR [ SET DATA ] TYPE \fIdata_type\fR [ COLLATE \fIcollation\fR ] [ USING \fIexpression\fR ]
57     ALTER [ COLUMN ] \fIcolumn_name\fR SET DEFAULT \fIexpression\fR
58     ALTER [ COLUMN ] \fIcolumn_name\fR DROP DEFAULT
59     ALTER [ COLUMN ] \fIcolumn_name\fR { SET | DROP } NOT NULL
60     ALTER [ COLUMN ] \fIcolumn_name\fR SET EXPRESSION AS ( \fIexpression\fR )
61     ALTER [ COLUMN ] \fIcolumn_name\fR DROP EXPRESSION [ IF EXISTS ]
62     ALTER [ COLUMN ] \fIcolumn_name\fR ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( \fIsequence_options\fR ) ]
63     ALTER [ COLUMN ] \fIcolumn_name\fR { SET GENERATED { ALWAYS | BY DEFAULT } | SET \fIsequence_option\fR | RESTART [ [ WITH ] \fIrestart\fR ] } [\&.\&.\&.]
64     ALTER [ COLUMN ] \fIcolumn_name\fR DROP IDENTITY [ IF EXISTS ]
65     ALTER [ COLUMN ] \fIcolumn_name\fR SET STATISTICS { \fIinteger\fR | DEFAULT }
66     ALTER [ COLUMN ] \fIcolumn_name\fR SET ( \fIattribute_option\fR = \fIvalue\fR [, \&.\&.\&. ] )
67     ALTER [ COLUMN ] \fIcolumn_name\fR RESET ( \fIattribute_option\fR [, \&.\&.\&. ] )
68     ALTER [ COLUMN ] \fIcolumn_name\fR SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT }
69     ALTER [ COLUMN ] \fIcolumn_name\fR SET COMPRESSION \fIcompression_method\fR
70     ADD \fItable_constraint\fR [ NOT VALID ]
71     ADD \fItable_constraint_using_index\fR
72     ALTER CONSTRAINT \fIconstraint_name\fR [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ ENFORCED | NOT ENFORCED ]
73     ALTER CONSTRAINT \fIconstraint_name\fR [ INHERIT | NO INHERIT ]
74     VALIDATE CONSTRAINT \fIconstraint_name\fR
75     DROP CONSTRAINT [ IF EXISTS ]  \fIconstraint_name\fR [ RESTRICT | CASCADE ]
76     DISABLE TRIGGER [ \fItrigger_name\fR | ALL | USER ]
77     ENABLE TRIGGER [ \fItrigger_name\fR | ALL | USER ]
78     ENABLE REPLICA TRIGGER \fItrigger_name\fR
79     ENABLE ALWAYS TRIGGER \fItrigger_name\fR
80     DISABLE RULE \fIrewrite_rule_name\fR
81     ENABLE RULE \fIrewrite_rule_name\fR
82     ENABLE REPLICA RULE \fIrewrite_rule_name\fR
83     ENABLE ALWAYS RULE \fIrewrite_rule_name\fR
84     DISABLE ROW LEVEL SECURITY
85     ENABLE ROW LEVEL SECURITY
86     FORCE ROW LEVEL SECURITY
87     NO FORCE ROW LEVEL SECURITY
88     CLUSTER ON \fIindex_name\fR
89     SET WITHOUT CLUSTER
90     SET WITHOUT OIDS
91     SET ACCESS METHOD { \fInew_access_method\fR | DEFAULT }
92     SET TABLESPACE \fInew_tablespace\fR
93     SET { LOGGED | UNLOGGED }
94     SET ( \fIstorage_parameter\fR [= \fIvalue\fR] [, \&.\&.\&. ] )
95     RESET ( \fIstorage_parameter\fR [, \&.\&.\&. ] )
96     INHERIT \fIparent_table\fR
97     NO INHERIT \fIparent_table\fR
98     OF \fItype_name\fR
99     NOT OF
100     OWNER TO { \fInew_owner\fR | CURRENT_ROLE | CURRENT_USER | SESSION_USER }
101     REPLICA IDENTITY { DEFAULT | USING INDEX \fIindex_name\fR | FULL | NOTHING }
102
103 and \fIpartition_bound_spec\fR is:
104
105 IN ( \fIpartition_bound_expr\fR [, \&.\&.\&.] ) |
106 FROM ( { \fIpartition_bound_expr\fR | MINVALUE | MAXVALUE } [, \&.\&.\&.] )
107   TO ( { \fIpartition_bound_expr\fR | MINVALUE | MAXVALUE } [, \&.\&.\&.] ) |
108 WITH ( MODULUS \fInumeric_literal\fR, REMAINDER \fInumeric_literal\fR )
109
110 and \fIcolumn_constraint\fR is:
111
112 [ CONSTRAINT \fIconstraint_name\fR ]
113 { NOT NULL [ NO INHERIT ] |
114   NULL |
115   CHECK ( \fIexpression\fR ) [ NO INHERIT ] |
116   DEFAULT \fIdefault_expr\fR |
117   GENERATED ALWAYS AS ( \fIgeneration_expr\fR ) [ STORED | VIRTUAL ] |
118   GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( \fIsequence_options\fR ) ] |
119   UNIQUE [ NULLS [ NOT ] DISTINCT ] \fIindex_parameters\fR |
120   PRIMARY KEY \fIindex_parameters\fR |
121   REFERENCES \fIreftable\fR [ ( \fIrefcolumn\fR ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
122     [ ON DELETE \fIreferential_action\fR ] [ ON UPDATE \fIreferential_action\fR ] }
123 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ ENFORCED | NOT ENFORCED ]
124
125 and \fItable_constraint\fR is:
126
127 [ CONSTRAINT \fIconstraint_name\fR ]
128 { CHECK ( \fIexpression\fR ) [ NO INHERIT ] |
129   NOT NULL \fIcolumn_name\fR [ NO INHERIT ] |
130   UNIQUE [ NULLS [ NOT ] DISTINCT ] ( \fIcolumn_name\fR [, \&.\&.\&. ] [, \fIcolumn_name\fR WITHOUT OVERLAPS ] ) \fIindex_parameters\fR |
131   PRIMARY KEY ( \fIcolumn_name\fR [, \&.\&.\&. ] [, \fIcolumn_name\fR WITHOUT OVERLAPS ] ) \fIindex_parameters\fR |
132   EXCLUDE [ USING \fIindex_method\fR ] ( \fIexclude_element\fR WITH \fIoperator\fR [, \&.\&.\&. ] ) \fIindex_parameters\fR [ WHERE ( \fIpredicate\fR ) ] |
133   FOREIGN KEY ( \fIcolumn_name\fR [, \&.\&.\&. ] [, PERIOD \fIcolumn_name\fR ] ) REFERENCES \fIreftable\fR [ ( \fIrefcolumn\fR [, \&.\&.\&. ]  [, PERIOD \fIrefcolumn\fR ] ) ]
134     [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE \fIreferential_action\fR ] [ ON UPDATE \fIreferential_action\fR ] }
135 [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ ENFORCED | NOT ENFORCED ]
136
137 and \fItable_constraint_using_index\fR is:
138
139     [ CONSTRAINT \fIconstraint_name\fR ]
140     { UNIQUE | PRIMARY KEY } USING INDEX \fIindex_name\fR
141     [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
142
143 \fIindex_parameters\fR in UNIQUE, PRIMARY KEY, and EXCLUDE constraints are:
144
145 [ INCLUDE ( \fIcolumn_name\fR [, \&.\&.\&. ] ) ]
146 [ WITH ( \fIstorage_parameter\fR [= \fIvalue\fR] [, \&.\&.\&. ] ) ]
147 [ USING INDEX TABLESPACE \fItablespace_name\fR ]
148
149 \fIexclude_element\fR in an EXCLUDE constraint is:
150
151 { \fIcolumn_name\fR | ( \fIexpression\fR ) } [ COLLATE \fIcollation\fR ] [ \fIopclass\fR [ ( \fIopclass_parameter\fR = \fIvalue\fR [, \&.\&.\&. ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]
152
153 \fIreferential_action\fR in a FOREIGN KEY/REFERENCES constraint is:
154
155 { NO ACTION | RESTRICT | CASCADE | SET NULL [ ( \fIcolumn_name\fR [, \&.\&.\&. ] ) ] | SET DEFAULT [ ( \fIcolumn_name\fR [, \&.\&.\&. ] ) ] }
156 .fi
157 .SH "DESCRIPTION"
158 .PP
159 \fBALTER TABLE\fR
160 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
161 ACCESS EXCLUSIVE
162 lock is acquired unless explicitly noted\&. When multiple subcommands are given, the lock acquired will be the strictest one required by any subcommand\&.
163 .PP
164 ADD COLUMN [ IF NOT EXISTS ]
165 .RS 4
166 This form adds a new column to the table, using the same syntax as
167 \fBCREATE TABLE\fR\&. If
168 IF NOT EXISTS
169 is specified and a column already exists with this name, no error is thrown\&.
170 .RE
171 .PP
172 DROP COLUMN [ IF EXISTS ]
173 .RS 4
174 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
175 CASCADE
176 if anything outside the table depends on the column, for example, foreign key references or views\&. If
177 IF EXISTS
178 is specified and the column does not exist, no error is thrown\&. In this case a notice is issued instead\&.
179 .RE
180 .PP
181 SET DATA TYPE
182 .RS 4
183 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
184 COLLATE
185 clause specifies a collation for the new column; if omitted, the collation is the default for the new column type\&. The optional
186 USING
187 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
188 USING
189 clause must be provided if there is no implicit or assignment cast from old to new type\&.
190 .sp
191 When this form is used, the column\*(Aqs statistics are removed, so running
192 \fBANALYZE\fR
193 on the table afterwards is recommended\&. For a virtual generated column,
194 \fBANALYZE\fR
195 is not necessary because such columns never have statistics\&.
196 .RE
197 .PP
198 SET/DROP DEFAULT
199 .RS 4
200 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
201 \fBINSERT\fR
202 or
203 \fBUPDATE\fR
204 commands; it does not cause rows already in the table to change\&.
205 .RE
206 .PP
207 SET/DROP NOT NULL
208 .RS 4
209 These forms change whether a column is marked to allow null values or to reject null values\&.
210 .sp
211 SET NOT NULL
212 may only be applied to a column provided none of the records in the table contain a
213 NULL
214 value for the column\&. Ordinarily this is checked during the
215 ALTER TABLE
216 by scanning the entire table, unless
217 NOT VALID
218 is specified; however, if a valid
219 CHECK
220 constraint exists (and is not dropped in the same command) which proves no
221 NULL
222 can exist, then the table scan is skipped\&. If a column has an invalid not\-null constraint,
223 SET NOT NULL
224 validates it\&.
225 .sp
226 If this table is a partition, one cannot perform
227 DROP NOT NULL
228 on a column if it is marked
229 NOT NULL
230 in the parent table\&. To drop the
231 NOT NULL
232 constraint from all the partitions, perform
233 DROP NOT NULL
234 on the parent table\&. Even if there is no
235 NOT NULL
236 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\&. It is also possible to drop the
237 NOT NULL
238 constraint from
239 ONLY
240 the parent table, which does not remove it from the children\&.
241 .RE
242 .PP
243 SET EXPRESSION AS
244 .RS 4
245 This form replaces the expression of a generated column\&. Existing data in a stored generated column is rewritten and all the future changes will apply the new generation expression\&.
246 .sp
247 When this form is used on a stored generated column, its statistics are removed, so running
248 \fBANALYZE\fR
249 on the table afterwards is recommended\&. For a virtual generated column,
250 \fBANALYZE\fR
251 is not necessary because such columns never have statistics\&.
252 .RE
253 .PP
254 DROP EXPRESSION [ IF EXISTS ]
255 .RS 4
256 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\&.
257 .sp
258 This form is currently only supported for stored generated columns (not virtual ones)\&.
259 .sp
260 If
261 DROP EXPRESSION IF EXISTS
262 is specified and the column is not a generated column, no error is thrown\&. In this case a notice is issued instead\&.
263 .RE
264 .PP
265 ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY
266 .br
267 SET GENERATED { ALWAYS | BY DEFAULT }
268 .br
269 DROP IDENTITY [ IF EXISTS ]
270 .RS 4
271 These forms change whether a column is an identity column or change the generation attribute of an existing identity column\&. See
272 \fBCREATE TABLE\fR
273 for details\&. Like
274 SET DEFAULT, these forms only affect the behavior of subsequent
275 \fBINSERT\fR
276 and
277 \fBUPDATE\fR
278 commands; they do not cause rows already in the table to change\&.
279 .sp
280 If
281 DROP IDENTITY IF EXISTS
282 is specified and the column is not an identity column, no error is thrown\&. In this case a notice is issued instead\&.
283 .RE
284 .PP
285 SET \fIsequence_option\fR
286 .br
287 RESTART
288 .RS 4
289 These forms alter the sequence that underlies an existing identity column\&.
290 \fIsequence_option\fR
291 is an option supported by
292 \fBALTER SEQUENCE\fR
293 such as
294 INCREMENT BY\&.
295 .RE
296 .PP
297 SET STATISTICS
298 .RS 4
299 This form sets the per\-column statistics\-gathering target for subsequent
300 \fBANALYZE\fR
301 operations\&. The target can be set in the range 0 to 10000\&. Set it to
302 DEFAULT
303 to revert to using the system default statistics target (default_statistics_target)\&. (Setting to a value of \-1 is an obsolete way spelling to get the same outcome\&.) For more information on the use of statistics by the
304 PostgreSQL
305 query planner, refer to
306 Section\ \&14.2\&.
307 .sp
308 SET STATISTICS
309 acquires a
310 SHARE UPDATE EXCLUSIVE
311 lock\&.
312 .RE
313 .PP
314 SET ( \fIattribute_option\fR = \fIvalue\fR [, \&.\&.\&. ] )
315 .br
316 RESET ( \fIattribute_option\fR [, \&.\&.\&. ] )
317 .RS 4
318 This form sets or resets per\-attribute options\&. Currently, the only defined per\-attribute options are
319 n_distinct
320 and
321 n_distinct_inherited, which override the number\-of\-distinct\-values estimates made by subsequent
322 \fBANALYZE\fR
323 operations\&.
324 n_distinct
325 affects the statistics for the table itself, while
326 n_distinct_inherited
327 affects the statistics gathered for the table plus its inheritance children\&. When set to a positive value,
328 \fBANALYZE\fR
329 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,
330 \fBANALYZE\fR
331 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
332 PostgreSQL
333 query planner, refer to
334 Section\ \&14.2\&.
335 .sp
336 Changing per\-attribute options acquires a
337 SHARE UPDATE EXCLUSIVE
338 lock\&.
339 .RE
340 .PP
341 SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT }
342 .RS 4
343 This form sets the storage mode for a column\&. This controls whether this column is held inline or in a secondary
344 TOAST
345 table, and whether the data should be compressed or not\&.
346 PLAIN
347 must be used for fixed\-length values such as
348 integer
349 and is inline, uncompressed\&.
350 MAIN
351 is for inline, compressible data\&.
352 EXTERNAL
353 is for external, uncompressed data, and
354 EXTENDED
355 is for external, compressed data\&. Writing
356 DEFAULT
357 sets the storage mode to the default mode for the column\*(Aqs data type\&.
358 EXTENDED
359 is the default for most data types that support non\-PLAIN
360 storage\&. Use of
361 EXTERNAL
362 will make substring operations on very large
363 text
364 and
365 bytea
366 values run faster, at the penalty of increased storage space\&. Note that
367 ALTER TABLE \&.\&.\&. SET STORAGE
368 doesn\*(Aqt itself change anything in the table; it just sets the strategy to be pursued during future table updates\&. See
369 Section\ \&66.2
370 for more information\&.
371 .RE
372 .PP
373 SET COMPRESSION \fIcompression_method\fR
374 .RS 4
375 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
376 pg_restore, then all values are rewritten with the configured compression method\&. However, when data is inserted from another relation (for example, by
377 \fBINSERT \&.\&.\&. SELECT\fR), 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
378 pglz
379 and
380 lz4\&. (lz4
381 is available only if
382 \fB\-\-with\-lz4\fR
383 was used when building
384 PostgreSQL\&.) In addition,
385 \fIcompression_method\fR
386 can be
387 default, which selects the default behavior of consulting the
388 default_toast_compression
389 setting at the time of data insertion to determine the method to use\&.
390 .RE
391 .PP
392 ADD \fItable_constraint\fR [ NOT VALID ]
393 .RS 4
394 This form adds a new constraint to a table using the same constraint syntax as
395 \fBCREATE TABLE\fR, plus the option
396 NOT VALID, which is currently only allowed for foreign\-key,
397 CHECK, and not\-null constraints\&.
398 .sp
399 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
400 NOT VALID
401 option is used, this potentially\-lengthy scan is skipped\&. The constraint will still be applied against subsequent inserts or updates (that is, they\*(Aqll fail unless there is a matching row in the referenced table, in the case of foreign keys, or they\*(Aqll 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
402 VALIDATE CONSTRAINT
403 option\&. See
404 Notes
405 below for more information about using the
406 NOT VALID
407 option\&.
408 .sp
409 Although most forms of
410 ADD \fItable_constraint\fR
411 require an
412 ACCESS EXCLUSIVE
413 lock,
414 ADD FOREIGN KEY
415 requires only a
416 SHARE ROW EXCLUSIVE
417 lock\&. Note that
418 ADD FOREIGN KEY
419 also acquires a
420 SHARE ROW EXCLUSIVE
421 lock on the referenced table, in addition to the lock on the table on which the constraint is declared\&.
422 .sp
423 Additional restrictions apply when unique or primary key constraints are added to partitioned tables; see
424 \fBCREATE TABLE\fR\&.
425 .RE
426 .PP
427 ADD \fItable_constraint_using_index\fR
428 .RS 4
429 This form adds a new
430 PRIMARY KEY
431 or
432 UNIQUE
433 constraint to a table based on an existing unique index\&. All the columns of the index will be included in the constraint\&.
434 .sp
435 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
436 ADD PRIMARY KEY
437 or
438 ADD UNIQUE
439 command\&.
440 .sp
441 If
442 PRIMARY KEY
443 is specified, and the index\*(Aqs columns are not already marked
444 NOT NULL, then this command will attempt to do
445 ALTER COLUMN SET NOT NULL
446 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\&.
447 .sp
448 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\&.
449 .sp
450 After this command is executed, the index is
451 \(lqowned\(rq
452 by the constraint, in the same way as if the index had been built by a regular
453 ADD PRIMARY KEY
454 or
455 ADD UNIQUE
456 command\&. In particular, dropping the constraint will make the index disappear too\&.
457 .sp
458 This form is not currently supported on partitioned tables\&.
459 .if n \{\
460 .sp
461 .\}
462 .RS 4
463 .it 1 an-trap
464 .nr an-no-space-flag 1
465 .nr an-break-flag 1
466 .br
467 .ps +1
468 \fBNote\fR
469 .ps -1
470 .br
471 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
472 \fBCREATE UNIQUE INDEX CONCURRENTLY\fR, and then convert it to a constraint using this syntax\&. See the example below\&.
473 .sp .5v
474 .RE
475 .RE
476 .PP
477 ALTER CONSTRAINT
478 .RS 4
479 This form alters the attributes of a constraint that was previously created\&. Currently only foreign key constraints may be altered in this fashion, but see below\&.
480 .RE
481 .PP
482 ALTER CONSTRAINT \&.\&.\&. INHERIT
483 .br
484 ALTER CONSTRAINT \&.\&.\&. NO INHERIT
485 .RS 4
486 These forms modify a inheritable constraint so that it becomes not inheritable, or vice\-versa\&. Only not\-null constraints may be altered in this fashion at present\&. In addition to changing the inheritability status of the constraint, in the case where a non\-inheritable constraint is being marked inheritable, if the table has children, an equivalent constraint will be added to them\&. If marking an inheritable constraint as non\-inheritable on a table with children, then the corresponding constraint on children will be marked as no longer inherited, but not removed\&.
487 .RE
488 .PP
489 VALIDATE CONSTRAINT
490 .RS 4
491 This form validates a foreign key, check, or not\-null constraint that was previously created as
492 NOT VALID, by scanning the table to ensure there are no rows for which the constraint is not satisfied\&. If the constraint was set to
493 NOT ENFORCED, an error is thrown\&. Nothing happens if the constraint is already marked valid\&. (See
494 Notes
495 below for an explanation of the usefulness of this command\&.)
496 .sp
497 This command acquires a
498 SHARE UPDATE EXCLUSIVE
499 lock\&.
500 .RE
501 .PP
502 DROP CONSTRAINT [ IF EXISTS ]
503 .RS 4
504 This form drops the specified constraint on a table, along with any index underlying the constraint\&. If
505 IF EXISTS
506 is specified and the constraint does not exist, no error is thrown\&. In this case a notice is issued instead\&.
507 .RE
508 .PP
509 DISABLE/ENABLE [ REPLICA | ALWAYS ] TRIGGER
510 .RS 4
511 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\&.
512 .sp
513 The trigger firing mechanism is also affected by the configuration variable
514 session_replication_role\&. Simply enabled triggers (the default) will fire when the replication role is
515 \(lqorigin\(rq
516 (the default) or
517 \(lqlocal\(rq\&. Triggers configured as
518 ENABLE REPLICA
519 will only fire if the session is in
520 \(lqreplica\(rq
521 mode, and triggers configured as
522 ENABLE ALWAYS
523 will fire regardless of the current replication role\&.
524 .sp
525 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
526 ENABLE ALWAYS
527 so that it is also fired on replicas\&.
528 .sp
529 When this command is applied to a partitioned table, the states of corresponding clone triggers in the partitions are updated too, unless
530 ONLY
531 is specified\&.
532 .sp
533 This command acquires a
534 SHARE ROW EXCLUSIVE
535 lock\&.
536 .RE
537 .PP
538 DISABLE/ENABLE [ REPLICA | ALWAYS ] RULE
539 .RS 4
540 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
541 ON SELECT
542 rules, which are always applied in order to keep views working even if the current session is in a non\-default replication role\&.
543 .sp
544 The rule firing mechanism is also affected by the configuration variable
545 session_replication_role, analogous to triggers as described above\&.
546 .RE
547 .PP
548 DISABLE/ENABLE ROW LEVEL SECURITY
549 .RS 4
550 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
551 \fInot\fR
552 be applied and the policies will be ignored\&. See also
553 \fBCREATE POLICY\fR\&.
554 .RE
555 .PP
556 NO FORCE/FORCE ROW LEVEL SECURITY
557 .RS 4
558 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
559 \fBCREATE POLICY\fR\&.
560 .RE
561 .PP
562 CLUSTER ON
563 .RS 4
564 This form selects the default index for future
565 \fBCLUSTER\fR
566 operations\&. It does not actually re\-cluster the table\&.
567 .sp
568 Changing cluster options acquires a
569 SHARE UPDATE EXCLUSIVE
570 lock\&.
571 .RE
572 .PP
573 SET WITHOUT CLUSTER
574 .RS 4
575 This form removes the most recently used
576 \fBCLUSTER\fR
577 index specification from the table\&. This affects future cluster operations that don\*(Aqt specify an index\&.
578 .sp
579 Changing cluster options acquires a
580 SHARE UPDATE EXCLUSIVE
581 lock\&.
582 .RE
583 .PP
584 SET WITHOUT OIDS
585 .RS 4
586 Backward\-compatible syntax for removing the
587 oid
588 system column\&. As
589 oid
590 system columns cannot be added anymore, this never has an effect\&.
591 .RE
592 .PP
593 SET ACCESS METHOD
594 .RS 4
595 This form changes the access method of the table by rewriting it using the indicated access method; specifying
596 DEFAULT
597 selects the access method set as the
598 default_table_access_method
599 configuration parameter\&. See
600 Chapter\ \&62
601 for more information\&.
602 .sp
603 When applied to a partitioned table, there is no data to rewrite, but partitions created afterwards will default to the given access method unless overridden by a
604 USING
605 clause\&. Specifying
606 \fIDEFAULT\fR
607 removes a previous value, causing future partitions to default to
608 \fIdefault_table_access_method\fR\&.
609 .RE
610 .PP
611 SET TABLESPACE
612 .RS 4
613 This form changes the table\*(Aqs 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
614 SET TABLESPACE
615 commands\&. When applied to a partitioned table, nothing is moved, but any partitions created afterwards with
616 \fBCREATE TABLE PARTITION OF\fR
617 will use that tablespace, unless overridden by a
618 TABLESPACE
619 clause\&.
620 .sp
621 All tables in the current database in a tablespace can be moved by using the
622 ALL IN TABLESPACE
623 form, which will lock all tables to be moved first and then move each one\&. This form also supports
624 OWNED BY, which will only move tables owned by the roles specified\&. If the
625 NOWAIT
626 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
627 \fBALTER DATABASE\fR
628 or explicit
629 \fBALTER TABLE\fR
630 invocations instead if desired\&. The
631 information_schema
632 relations are not considered part of the system catalogs and will be moved\&. See also
633 \fBCREATE TABLESPACE\fR\&.
634 .RE
635 .PP
636 SET { LOGGED | UNLOGGED }
637 .RS 4
638 This form changes the table from unlogged to logged or vice\-versa (see
639 UNLOGGED)\&. It cannot be applied to a temporary table\&.
640 .sp
641 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\&.
642 .sp
643 This form is not supported for partitioned tables\&.
644 .RE
645 .PP
646 SET ( \fIstorage_parameter\fR [= \fIvalue\fR] [, \&.\&.\&. ] )
647 .RS 4
648 This form changes one or more storage parameters for the table\&. See
649 Storage Parameters
650 in the
651 \fBCREATE TABLE\fR
652 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
653 \fBVACUUM FULL\fR,
654 \fBCLUSTER\fR
655 or one of the forms of
656 \fBALTER TABLE\fR
657 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\&.
658 .sp
659 SHARE UPDATE EXCLUSIVE
660 lock will be taken for fillfactor, toast and autovacuum storage parameters, as well as the planner parameter
661 \fIparallel_workers\fR\&.
662 .RE
663 .PP
664 RESET ( \fIstorage_parameter\fR [, \&.\&.\&. ] )
665 .RS 4
666 This form resets one or more storage parameters to their defaults\&. As with
667 SET, a table rewrite might be needed to update the table entirely\&.
668 .RE
669 .PP
670 INHERIT \fIparent_table\fR
671 .RS 4
672 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\&.
673 .sp
674 In addition, all
675 CHECK
676 and
677 NOT NULL
678 constraints on the parent must also exist on the child, except those marked non\-inheritable (that is, created with
679 ALTER TABLE \&.\&.\&. ADD CONSTRAINT \&.\&.\&. NO INHERIT), which are ignored\&. All child\-table constraints matched must not be marked non\-inheritable\&. Currently
680 UNIQUE,
681 PRIMARY KEY, and
682 FOREIGN KEY
683 constraints are not considered, but this might change in the future\&.
684 .RE
685 .PP
686 NO INHERIT \fIparent_table\fR
687 .RS 4
688 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\&.
689 .RE
690 .PP
691 OF \fItype_name\fR
692 .RS 4
693 This form links the table to a composite type as though
694 \fBCREATE TABLE OF\fR
695 had formed it\&. The table\*(Aqs 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
696 \fBCREATE TABLE OF\fR
697 would permit an equivalent table definition\&.
698 .RE
699 .PP
700 NOT OF
701 .RS 4
702 This form dissociates a typed table from its type\&.
703 .RE
704 .PP
705 OWNER TO
706 .RS 4
707 This form changes the owner of the table, sequence, view, materialized view, or foreign table to the specified user\&.
708 .RE
709 .PP
710 REPLICA IDENTITY
711 .RS 4
712 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\&.
713 .PP
714 DEFAULT
715 .RS 4
716 Records the old values of the columns of the primary key\&. This is the default for non\-system tables\&. When there is no primary key, the behavior is the same as
717 NOTHING\&.
718 .RE
719 .PP
720 USING INDEX \fIindex_name\fR
721 .RS 4
722 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
723 NOT NULL\&. If this index is dropped, the behavior is the same as
724 NOTHING\&.
725 .RE
726 .PP
727 FULL
728 .RS 4
729 Records the old values of all columns in the row\&.
730 .RE
731 .PP
732 NOTHING
733 .RS 4
734 Records no information about the old row\&. This is the default for system tables\&.
735 .RE
736 .RE
737 .PP
738 RENAME
739 .RS 4
740 The
741 RENAME
742 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\&.
743 .RE
744 .PP
745 SET SCHEMA
746 .RS 4
747 This form moves the table into another schema\&. Associated indexes, constraints, and sequences owned by table columns are moved as well\&.
748 .RE
749 .PP
750 ATTACH PARTITION \fIpartition_name\fR { FOR VALUES \fIpartition_bound_spec\fR | DEFAULT }
751 .RS 4
752 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
753 FOR VALUES
754 or as a default partition by using
755 DEFAULT\&. 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\*(Aqs index, as if
756 \fBALTER INDEX ATTACH PARTITION\fR
757 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
758 UNIQUE
759 indexes on the target table\&. (See also
760 CREATE FOREIGN TABLE (\fBCREATE_FOREIGN_TABLE\fR(7))\&.) For each user\-defined row\-level trigger that exists in the target table, a corresponding one is created in the attached table\&.
761 .sp
762 A partition using
763 FOR VALUES
764 uses same syntax for
765 \fIpartition_bound_spec\fR
766 as
767 \fBCREATE TABLE\fR\&. 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
768 NOT NULL
769 and
770 CHECK
771 constraints of the target table, not marked
772 NO INHERIT\&. Currently
773 FOREIGN KEY
774 constraints are not considered\&.
775 UNIQUE
776 and
777 PRIMARY KEY
778 constraints from the parent table will be created in the partition, if they don\*(Aqt already exist\&.
779 .sp
780 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
781 CHECK
782 constraint to the table that allows only rows satisfying the desired partition constraint before running this command\&. The
783 CHECK
784 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
785 NULL
786 values\&. If attaching a list partition that will not accept
787 NULL
788 values, also add a
789 NOT NULL
790 constraint to the partition key column, unless it\*(Aqs an expression\&.
791 .sp
792 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
793 CREATE FOREIGN TABLE (\fBCREATE_FOREIGN_TABLE\fR(7))
794 about constraints on the foreign table\&.)
795 .sp
796 When a table has a default partition, defining a new partition changes the partition constraint for the default partition\&. The default partition can\*(Aqt 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
797 CHECK
798 constraint is present\&. Also like the scan of the new partition, it is always skipped when the default partition is a foreign table\&.
799 .sp
800 Attaching a partition acquires a
801 SHARE UPDATE EXCLUSIVE
802 lock on the parent table, in addition to the
803 ACCESS EXCLUSIVE
804 locks on the table being attached and on the default partition (if any)\&.
805 .sp
806 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
807 CHECK
808 constraint as described in
809 Section\ \&5.12.2.2\&.
810 .RE
811 .PP
812 DETACH PARTITION \fIpartition_name\fR [ CONCURRENTLY | FINALIZE ]
813 .RS 4
814 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\*(Aqs indexes are detached\&. Any triggers that were created as clones of those in the target table are removed\&.
815 SHARE
816 lock is obtained on any tables that reference this partitioned table in foreign key constraints\&.
817 .sp
818 If
819 CONCURRENTLY
820 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
821 SHARE UPDATE EXCLUSIVE
822 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
823 SHARE UPDATE EXCLUSIVE
824 on the partitioned table and
825 ACCESS EXCLUSIVE
826 on the partition, and the detach process completes\&. A
827 CHECK
828 constraint that duplicates the partition constraint is added to the partition\&.
829 CONCURRENTLY
830 cannot be run in a transaction block and is not allowed if the partitioned table contains a default partition\&.
831 .sp
832 If
833 FINALIZE
834 is specified, a previous
835 DETACH CONCURRENTLY
836 invocation that was canceled or interrupted is completed\&. At most one partition in a partitioned table can be pending detach at a time\&.
837 .RE
838 .PP
839 All the forms of
840 \fBALTER TABLE\fR
841 that act on a single table, except
842 RENAME,
843 SET SCHEMA,
844 ATTACH PARTITION, and
845 DETACH PARTITION
846 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\&.
847 .PP
848 You must own the table to use
849 \fBALTER TABLE\fR\&. To change the schema or tablespace of a table, you must also have
850 CREATE
851 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
852 SET ROLE
853 to the new owning role, and that role must have
854 CREATE
855 privilege on the table\*(Aqs schema\&. (These restrictions enforce that altering the owner doesn\*(Aqt do anything you couldn\*(Aqt 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
856 OF
857 clause, you must also have
858 USAGE
859 privilege on the data type\&.
860 .SH "PARAMETERS"
861 .PP
862 IF EXISTS
863 .RS 4
864 Do not throw an error if the table does not exist\&. A notice is issued in this case\&.
865 .RE
866 .PP
867 \fIname\fR
868 .RS 4
869 The name (optionally schema\-qualified) of an existing table to alter\&. If
870 ONLY
871 is specified before the table name, only that table is altered\&. If
872 ONLY
873 is not specified, the table and all its descendant tables (if any) are altered\&. Optionally,
874 *
875 can be specified after the table name to explicitly indicate that descendant tables are included\&.
876 .RE
877 .PP
878 \fIcolumn_name\fR
879 .RS 4
880 Name of a new or existing column\&.
881 .RE
882 .PP
883 \fInew_column_name\fR
884 .RS 4
885 New name for an existing column\&.
886 .RE
887 .PP
888 \fInew_name\fR
889 .RS 4
890 New name for the table\&.
891 .RE
892 .PP
893 \fIdata_type\fR
894 .RS 4
895 Data type of the new column, or new data type for an existing column\&.
896 .RE
897 .PP
898 \fItable_constraint\fR
899 .RS 4
900 New table constraint for the table\&.
901 .RE
902 .PP
903 \fIconstraint_name\fR
904 .RS 4
905 Name of a new or existing constraint\&.
906 .RE
907 .PP
908 CASCADE
909 .RS 4
910 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
911 Section\ \&5.15)\&.
912 .RE
913 .PP
914 RESTRICT
915 .RS 4
916 Refuse to drop the column or constraint if there are any dependent objects\&. This is the default behavior\&.
917 .RE
918 .PP
919 \fItrigger_name\fR
920 .RS 4
921 Name of a single trigger to disable or enable\&.
922 .RE
923 .PP
924 ALL
925 .RS 4
926 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\&.)
927 .RE
928 .PP
929 USER
930 .RS 4
931 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\&.
932 .RE
933 .PP
934 \fIindex_name\fR
935 .RS 4
936 The name of an existing index\&.
937 .RE
938 .PP
939 \fIstorage_parameter\fR
940 .RS 4
941 The name of a table storage parameter\&.
942 .RE
943 .PP
944 \fIvalue\fR
945 .RS 4
946 The new value for a table storage parameter\&. This might be a number or a word depending on the parameter\&.
947 .RE
948 .PP
949 \fIparent_table\fR
950 .RS 4
951 A parent table to associate or de\-associate with this table\&.
952 .RE
953 .PP
954 \fInew_owner\fR
955 .RS 4
956 The user name of the new owner of the table\&.
957 .RE
958 .PP
959 \fInew_access_method\fR
960 .RS 4
961 The name of the access method to which the table will be converted\&.
962 .RE
963 .PP
964 \fInew_tablespace\fR
965 .RS 4
966 The name of the tablespace to which the table will be moved\&.
967 .RE
968 .PP
969 \fInew_schema\fR
970 .RS 4
971 The name of the schema to which the table will be moved\&.
972 .RE
973 .PP
974 \fIpartition_name\fR
975 .RS 4
976 The name of the table to attach as a new partition or to detach from this table\&.
977 .RE
978 .PP
979 \fIpartition_bound_spec\fR
980 .RS 4
981 The partition bound specification for a new partition\&. Refer to
982 CREATE TABLE (\fBCREATE_TABLE\fR(7))
983 for more details on the syntax of the same\&.
984 .RE
985 .SH "NOTES"
986 .PP
987 The key word
988 COLUMN
989 is noise and can be omitted\&.
990 .PP
991 When a column is added with
992 ADD COLUMN
993 and a non\-volatile
994 DEFAULT
995 is specified, the default value is evaluated at the time of the statement and the result stored in the table\*(Aqs metadata, where it will be returned when any existing rows are accessed\&. The value will be only applied when the table is rewritten, making the
996 \fBALTER TABLE\fR
997 very fast even on large tables\&. If no column constraints are specified, NULL is used as the
998 DEFAULT\&. In neither case is a rewrite of the table required\&.
999 .PP
1000 Adding a column with a volatile
1001 DEFAULT
1002 (e\&.g\&.,
1003 \fBclock_timestamp()\fR), a stored generated column, an identity column, or a column with a domain data type that has constraints will cause the entire table and its indexes to be rewritten\&. Adding a virtual generated column never requires a rewrite\&.
1004 .PP
1005 Changing the type of an existing column will normally cause the entire table and its indexes to be rewritten\&. As an exception, when changing the type of an existing column, if the
1006 USING
1007 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 will still 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 required because the new sort order might be different\&. However, in the absence of a collation change, a column can be changed from
1008 text
1009 to
1010 varchar
1011 (or vice versa) without rebuilding the indexes because these data types sort identically\&.
1012 .PP
1013 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\&.
1014 .PP
1015 Adding a
1016 CHECK
1017 or
1018 NOT NULL
1019 constraint requires scanning the table to verify that existing rows meet the constraint, but does not require a table rewrite\&. If a
1020 CHECK
1021 constraint is added as
1022 NOT ENFORCED, no verification will be performed\&.
1023 .PP
1024 Similarly, when attaching a new partition it may be scanned to verify that existing rows meet the partition constraint\&.
1025 .PP
1026 The main reason for providing the option to specify multiple changes in a single
1027 \fBALTER TABLE\fR
1028 is that multiple table scans or rewrites can thereby be combined into a single pass over the table\&.
1029 .PP
1030 Scanning a large table to verify new foreign\-key, check, or not\-null constraints can take a long time, and other updates to the table are locked out until the
1031 \fBALTER TABLE ADD CONSTRAINT\fR
1032 command is committed\&. The main purpose of the
1033 NOT VALID
1034 constraint option is to reduce the impact of adding a constraint on concurrent updates\&. With
1035 NOT VALID, the
1036 \fBADD CONSTRAINT\fR
1037 command does not scan the table and can be committed immediately\&. After that, a
1038 VALIDATE CONSTRAINT
1039 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
1040 SHARE UPDATE EXCLUSIVE
1041 lock on the table being altered\&. (If the constraint is a foreign key then a
1042 ROW SHARE
1043 lock is also required on the table referenced by the constraint\&.) In addition to improving concurrency, it can be useful to use
1044 NOT VALID
1045 and
1046 VALIDATE CONSTRAINT
1047 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
1048 VALIDATE CONSTRAINT
1049 finally succeeds\&.
1050 .PP
1051 The
1052 DROP COLUMN
1053 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\&.
1054 .PP
1055 To force immediate reclamation of space occupied by a dropped column, you can execute one of the forms of
1056 \fBALTER TABLE\fR
1057 that performs a rewrite of the whole table\&. This results in reconstructing each row with the dropped column replaced by a null value\&.
1058 .PP
1059 The rewriting forms of
1060 \fBALTER TABLE\fR
1061 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
1062 Section\ \&13.6
1063 for more details\&.
1064 .PP
1065 The
1066 USING
1067 option of
1068 SET DATA TYPE
1069 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
1070 SET DATA TYPE
1071 syntax\&. Because of this flexibility, the
1072 USING
1073 expression is not applied to the column\*(Aqs 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,
1074 SET DATA TYPE
1075 might fail to convert the default even though a
1076 USING
1077 clause is supplied\&. In such cases, drop the default with
1078 DROP DEFAULT, perform the
1079 ALTER TYPE, and then use
1080 SET DEFAULT
1081 to add a suitable new default\&. Similar considerations apply to indexes and constraints involving the column\&.
1082 .PP
1083 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
1084 CHECK
1085 constraint cannot be renamed in the parent without also renaming it in all descendants, so that
1086 CHECK
1087 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,
1088 \fBALTER TABLE ONLY\fR
1089 will be rejected\&.
1090 .PP
1091 A recursive
1092 DROP COLUMN
1093 operation will remove a descendant table\*(Aqs 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
1094 DROP COLUMN
1095 (i\&.e\&.,
1096 \fBALTER TABLE ONLY \&.\&.\&. DROP COLUMN\fR) never removes any descendant columns, but instead marks them as independently defined rather than inherited\&. A nonrecursive
1097 DROP COLUMN
1098 command will fail for a partitioned table, because all partitions of a table must have the same columns as the partitioning root\&.
1099 .PP
1100 The actions for identity columns (ADD GENERATED,
1101 SET
1102 etc\&.,
1103 DROP IDENTITY), as well as the actions
1104 CLUSTER,
1105 OWNER, and
1106 TABLESPACE
1107 never recurse to descendant tables; that is, they always act as though
1108 ONLY
1109 were specified\&. Actions affecting trigger states recurse to partitions of partitioned tables (unless
1110 ONLY
1111 is specified), but never to traditional\-inheritance descendants\&. Adding a constraint recurses only for
1112 CHECK
1113 constraints that are not marked
1114 NO INHERIT\&.
1115 .PP
1116 Changing any part of a system catalog table is not permitted\&.
1117 .PP
1118 Refer to
1119 CREATE TABLE (\fBCREATE_TABLE\fR(7))
1120 for a further description of valid parameters\&.
1121 Chapter\ \&5
1122 has further information on inheritance\&.
1123 .SH "EXAMPLES"
1124 .PP
1125 To add a column of type
1126 varchar
1127 to a table:
1128 .sp
1129 .if n \{\
1130 .RS 4
1131 .\}
1132 .nf
1133 ALTER TABLE distributors ADD COLUMN address varchar(30);
1134 .fi
1135 .if n \{\
1136 .RE
1137 .\}
1138 .sp
1139 That will cause all existing rows in the table to be filled with null values for the new column\&.
1140 .PP
1141 To add a column with a non\-null default:
1142 .sp
1143 .if n \{\
1144 .RS 4
1145 .\}
1146 .nf
1147 ALTER TABLE measurements
1148   ADD COLUMN mtime timestamp with time zone DEFAULT now();
1149 .fi
1150 .if n \{\
1151 .RE
1152 .\}
1153 .sp
1154 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\&.
1155 .PP
1156 To add a column and fill it with a value different from the default to be used later:
1157 .sp
1158 .if n \{\
1159 .RS 4
1160 .\}
1161 .nf
1162 ALTER TABLE transactions
1163   ADD COLUMN status varchar(30) DEFAULT \*(Aqold\*(Aq,
1164   ALTER COLUMN status SET default \*(Aqcurrent\*(Aq;
1165 .fi
1166 .if n \{\
1167 .RE
1168 .\}
1169 .sp
1170 Existing rows will be filled with
1171 old, but then the default for subsequent commands will be
1172 current\&. The effects are the same as if the two sub\-commands had been issued in separate
1173 \fBALTER TABLE\fR
1174 commands\&.
1175 .PP
1176 To drop a column from a table:
1177 .sp
1178 .if n \{\
1179 .RS 4
1180 .\}
1181 .nf
1182 ALTER TABLE distributors DROP COLUMN address RESTRICT;
1183 .fi
1184 .if n \{\
1185 .RE
1186 .\}
1187 .PP
1188 To change the types of two existing columns in one operation:
1189 .sp
1190 .if n \{\
1191 .RS 4
1192 .\}
1193 .nf
1194 ALTER TABLE distributors
1195     ALTER COLUMN address TYPE varchar(80),
1196     ALTER COLUMN name TYPE varchar(100);
1197 .fi
1198 .if n \{\
1199 .RE
1200 .\}
1201 .PP
1202 To change an integer column containing Unix timestamps to
1203 timestamp with time zone
1204 via a
1205 USING
1206 clause:
1207 .sp
1208 .if n \{\
1209 .RS 4
1210 .\}
1211 .nf
1212 ALTER TABLE foo
1213     ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone
1214     USING
1215         timestamp with time zone \*(Aqepoch\*(Aq + foo_timestamp * interval \*(Aq1 second\*(Aq;
1216 .fi
1217 .if n \{\
1218 .RE
1219 .\}
1220 .PP
1221 The same, when the column has a default expression that won\*(Aqt automatically cast to the new data type:
1222 .sp
1223 .if n \{\
1224 .RS 4
1225 .\}
1226 .nf
1227 ALTER TABLE foo
1228     ALTER COLUMN foo_timestamp DROP DEFAULT,
1229     ALTER COLUMN foo_timestamp TYPE timestamp with time zone
1230     USING
1231         timestamp with time zone \*(Aqepoch\*(Aq + foo_timestamp * interval \*(Aq1 second\*(Aq,
1232     ALTER COLUMN foo_timestamp SET DEFAULT now();
1233 .fi
1234 .if n \{\
1235 .RE
1236 .\}
1237 .PP
1238 To rename an existing column:
1239 .sp
1240 .if n \{\
1241 .RS 4
1242 .\}
1243 .nf
1244 ALTER TABLE distributors RENAME COLUMN address TO city;
1245 .fi
1246 .if n \{\
1247 .RE
1248 .\}
1249 .PP
1250 To rename an existing table:
1251 .sp
1252 .if n \{\
1253 .RS 4
1254 .\}
1255 .nf
1256 ALTER TABLE distributors RENAME TO suppliers;
1257 .fi
1258 .if n \{\
1259 .RE
1260 .\}
1261 .PP
1262 To rename an existing constraint:
1263 .sp
1264 .if n \{\
1265 .RS 4
1266 .\}
1267 .nf
1268 ALTER TABLE distributors RENAME CONSTRAINT zipchk TO zip_check;
1269 .fi
1270 .if n \{\
1271 .RE
1272 .\}
1273 .PP
1274 To add a not\-null constraint to a column:
1275 .sp
1276 .if n \{\
1277 .RS 4
1278 .\}
1279 .nf
1280 ALTER TABLE distributors ALTER COLUMN street SET NOT NULL;
1281 .fi
1282 .if n \{\
1283 .RE
1284 .\}
1285 .sp
1286 To remove a not\-null constraint from a column:
1287 .sp
1288 .if n \{\
1289 .RS 4
1290 .\}
1291 .nf
1292 ALTER TABLE distributors ALTER COLUMN street DROP NOT NULL;
1293 .fi
1294 .if n \{\
1295 .RE
1296 .\}
1297 .PP
1298 To add a check constraint to a table and all its children:
1299 .sp
1300 .if n \{\
1301 .RS 4
1302 .\}
1303 .nf
1304 ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5);
1305 .fi
1306 .if n \{\
1307 .RE
1308 .\}
1309 .PP
1310 To add a check constraint only to a table and not to its children:
1311 .sp
1312 .if n \{\
1313 .RS 4
1314 .\}
1315 .nf
1316 ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT;
1317 .fi
1318 .if n \{\
1319 .RE
1320 .\}
1321 .sp
1322 (The check constraint will not be inherited by future children, either\&.)
1323 .PP
1324 To remove a check constraint from a table and all its children:
1325 .sp
1326 .if n \{\
1327 .RS 4
1328 .\}
1329 .nf
1330 ALTER TABLE distributors DROP CONSTRAINT zipchk;
1331 .fi
1332 .if n \{\
1333 .RE
1334 .\}
1335 .PP
1336 To remove a check constraint from one table only:
1337 .sp
1338 .if n \{\
1339 .RS 4
1340 .\}
1341 .nf
1342 ALTER TABLE ONLY distributors DROP CONSTRAINT zipchk;
1343 .fi
1344 .if n \{\
1345 .RE
1346 .\}
1347 .sp
1348 (The check constraint remains in place for any child tables\&.)
1349 .PP
1350 To add a foreign key constraint to a table:
1351 .sp
1352 .if n \{\
1353 .RS 4
1354 .\}
1355 .nf
1356 ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);
1357 .fi
1358 .if n \{\
1359 .RE
1360 .\}
1361 .PP
1362 To add a foreign key constraint to a table with the least impact on other work:
1363 .sp
1364 .if n \{\
1365 .RS 4
1366 .\}
1367 .nf
1368 ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID;
1369 ALTER TABLE distributors VALIDATE CONSTRAINT distfk;
1370 .fi
1371 .if n \{\
1372 .RE
1373 .\}
1374 .PP
1375 To add a (multicolumn) unique constraint to a table:
1376 .sp
1377 .if n \{\
1378 .RS 4
1379 .\}
1380 .nf
1381 ALTER TABLE distributors ADD CONSTRAINT dist_id_zipcode_key UNIQUE (dist_id, zipcode);
1382 .fi
1383 .if n \{\
1384 .RE
1385 .\}
1386 .PP
1387 To add an automatically named primary key constraint to a table, noting that a table can only ever have one primary key:
1388 .sp
1389 .if n \{\
1390 .RS 4
1391 .\}
1392 .nf
1393 ALTER TABLE distributors ADD PRIMARY KEY (dist_id);
1394 .fi
1395 .if n \{\
1396 .RE
1397 .\}
1398 .PP
1399 To move a table to a different tablespace:
1400 .sp
1401 .if n \{\
1402 .RS 4
1403 .\}
1404 .nf
1405 ALTER TABLE distributors SET TABLESPACE fasttablespace;
1406 .fi
1407 .if n \{\
1408 .RE
1409 .\}
1410 .PP
1411 To move a table to a different schema:
1412 .sp
1413 .if n \{\
1414 .RS 4
1415 .\}
1416 .nf
1417 ALTER TABLE myschema\&.distributors SET SCHEMA yourschema;
1418 .fi
1419 .if n \{\
1420 .RE
1421 .\}
1422 .PP
1423 To recreate a primary key constraint, without blocking updates while the index is rebuilt:
1424 .sp
1425 .if n \{\
1426 .RS 4
1427 .\}
1428 .nf
1429 CREATE UNIQUE INDEX CONCURRENTLY dist_id_temp_idx ON distributors (dist_id);
1430 ALTER TABLE distributors DROP CONSTRAINT distributors_pkey,
1431     ADD CONSTRAINT distributors_pkey PRIMARY KEY USING INDEX dist_id_temp_idx;
1432 .fi
1433 .if n \{\
1434 .RE
1435 .\}
1436 .PP
1437 To attach a partition to a range\-partitioned table:
1438 .sp
1439 .if n \{\
1440 .RS 4
1441 .\}
1442 .nf
1443 ALTER TABLE measurement
1444     ATTACH PARTITION measurement_y2016m07 FOR VALUES FROM (\*(Aq2016\-07\-01\*(Aq) TO (\*(Aq2016\-08\-01\*(Aq);
1445 .fi
1446 .if n \{\
1447 .RE
1448 .\}
1449 .PP
1450 To attach a partition to a list\-partitioned table:
1451 .sp
1452 .if n \{\
1453 .RS 4
1454 .\}
1455 .nf
1456 ALTER TABLE cities
1457     ATTACH PARTITION cities_ab FOR VALUES IN (\*(Aqa\*(Aq, \*(Aqb\*(Aq);
1458 .fi
1459 .if n \{\
1460 .RE
1461 .\}
1462 .PP
1463 To attach a partition to a hash\-partitioned table:
1464 .sp
1465 .if n \{\
1466 .RS 4
1467 .\}
1468 .nf
1469 ALTER TABLE orders
1470     ATTACH PARTITION orders_p4 FOR VALUES WITH (MODULUS 4, REMAINDER 3);
1471 .fi
1472 .if n \{\
1473 .RE
1474 .\}
1475 .PP
1476 To attach a default partition to a partitioned table:
1477 .sp
1478 .if n \{\
1479 .RS 4
1480 .\}
1481 .nf
1482 ALTER TABLE cities
1483     ATTACH PARTITION cities_partdef DEFAULT;
1484 .fi
1485 .if n \{\
1486 .RE
1487 .\}
1488 .PP
1489 To detach a partition from a partitioned table:
1490 .sp
1491 .if n \{\
1492 .RS 4
1493 .\}
1494 .nf
1495 ALTER TABLE measurement
1496     DETACH PARTITION measurement_y2015m12;
1497 .fi
1498 .if n \{\
1499 .RE
1500 .\}
1501 .SH "COMPATIBILITY"
1502 .PP
1503 The forms
1504 ADD [COLUMN],
1505 DROP [COLUMN],
1506 DROP IDENTITY,
1507 RESTART,
1508 SET DEFAULT,
1509 SET DATA TYPE
1510 (without
1511 USING),
1512 SET GENERATED, and
1513 SET \fIsequence_option\fR
1514 conform with the SQL standard\&. The form
1515 ADD \fItable_constraint\fR
1516 conforms with the SQL standard when the
1517 USING INDEX
1518 and
1519 NOT VALID
1520 clauses are omitted and the constraint type is one of
1521 CHECK,
1522 UNIQUE,
1523 PRIMARY KEY, or
1524 REFERENCES\&. The other forms are
1525 PostgreSQL
1526 extensions of the SQL standard\&. Also, the ability to specify more than one manipulation in a single
1527 \fBALTER TABLE\fR
1528 command is an extension\&.
1529 .PP
1530 \fBALTER TABLE DROP COLUMN\fR
1531 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\&.
1532 .SH "SEE ALSO"
1533 CREATE TABLE (\fBCREATE_TABLE\fR(7))