{
    "mode": "man",
    "parameter": "ALTER_TABLE",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/ALTER_TABLE/7/json",
    "generated": "2026-07-06T02:03:46Z",
    "synopsis": "ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\naction [, ... ]\nALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\nRENAME [ COLUMN ] columnname TO newcolumnname\nALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\nRENAME CONSTRAINT constraintname TO newconstraintname\nALTER TABLE [ IF EXISTS ] name\nRENAME TO newname\nALTER TABLE [ IF EXISTS ] name\nSET SCHEMA newschema\nALTER TABLE ALL IN TABLESPACE name [ OWNED BY rolename [, ... ] ]\nSET TABLESPACE newtablespace [ NOWAIT ]\nALTER TABLE [ IF EXISTS ] name\nATTACH PARTITION partitionname { FOR VALUES partitionboundspec | DEFAULT }\nALTER TABLE [ IF EXISTS ] name\nDETACH PARTITION partitionname [ CONCURRENTLY | FINALIZE ]\nwhere action is one of:\nADD [ COLUMN ] [ IF NOT EXISTS ] columnname datatype [ COLLATE collation ] [ columnconstraint [ ... ] ]\nDROP [ COLUMN ] [ IF EXISTS ] columnname [ RESTRICT | CASCADE ]\nALTER [ COLUMN ] columnname [ SET DATA ] TYPE datatype [ COLLATE collation ] [ USING expression ]\nALTER [ COLUMN ] columnname SET DEFAULT expression\nALTER [ COLUMN ] columnname DROP DEFAULT\nALTER [ COLUMN ] columnname { SET | DROP } NOT NULL\nALTER [ COLUMN ] columnname DROP EXPRESSION [ IF EXISTS ]\nALTER [ COLUMN ] columnname ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequenceoptions ) ]\nALTER [ COLUMN ] columnname { SET GENERATED { ALWAYS | BY DEFAULT } | SET sequenceoption | RESTART [ [ WITH ] restart ] } [...]\nALTER [ COLUMN ] columnname DROP IDENTITY [ IF EXISTS ]\nALTER [ COLUMN ] columnname SET STATISTICS integer\nALTER [ COLUMN ] columnname SET ( attributeoption = value [, ... ] )\nALTER [ COLUMN ] columnname RESET ( attributeoption [, ... ] )\nALTER [ COLUMN ] columnname SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }\nALTER [ COLUMN ] columnname SET COMPRESSION compressionmethod\nADD tableconstraint [ NOT VALID ]\nADD tableconstraintusingindex\nALTER CONSTRAINT constraintname [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\nVALIDATE CONSTRAINT constraintname\nDROP CONSTRAINT [ IF EXISTS ]  constraintname [ RESTRICT | CASCADE ]\nDISABLE TRIGGER [ triggername | ALL | USER ]\nENABLE TRIGGER [ triggername | ALL | USER ]\nENABLE REPLICA TRIGGER triggername\nENABLE ALWAYS TRIGGER triggername\nDISABLE RULE rewriterulename\nENABLE RULE rewriterulename\nENABLE REPLICA RULE rewriterulename\nENABLE ALWAYS RULE rewriterulename\nDISABLE ROW LEVEL SECURITY\nENABLE ROW LEVEL SECURITY\nFORCE ROW LEVEL SECURITY\nNO FORCE ROW LEVEL SECURITY\nCLUSTER ON indexname\nSET WITHOUT CLUSTER\nSET WITHOUT OIDS\nSET TABLESPACE newtablespace\nSET { LOGGED | UNLOGGED }\nSET ( storageparameter [= value] [, ... ] )\nRESET ( storageparameter [, ... ] )\nINHERIT parenttable\nNO INHERIT parenttable\nOF typename\nNOT OF\nOWNER TO { newowner | CURRENTROLE | CURRENTUSER | SESSIONUSER }\nREPLICA IDENTITY { DEFAULT | USING INDEX indexname | FULL | NOTHING }\nand partitionboundspec is:\nIN ( partitionboundexpr [, ...] ) |\nFROM ( { partitionboundexpr | MINVALUE | MAXVALUE } [, ...] )\nTO ( { partitionboundexpr | MINVALUE | MAXVALUE } [, ...] ) |\nWITH ( MODULUS numericliteral, REMAINDER numericliteral )\nand columnconstraint is:\n[ CONSTRAINT constraintname ]\n{ NOT NULL |\nNULL |\nCHECK ( expression ) [ NO INHERIT ] |\nDEFAULT defaultexpr |\nGENERATED ALWAYS AS ( generationexpr ) STORED |\nGENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequenceoptions ) ] |\nUNIQUE indexparameters |\nPRIMARY KEY indexparameters |\nREFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]\n[ ON DELETE referentialaction ] [ ON UPDATE referentialaction ] }\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\nand tableconstraint is:\n[ CONSTRAINT constraintname ]\n{ CHECK ( expression ) [ NO INHERIT ] |\nUNIQUE ( columnname [, ... ] ) indexparameters |\nPRIMARY KEY ( columnname [, ... ] ) indexparameters |\nEXCLUDE [ USING indexmethod ] ( excludeelement WITH operator [, ... ] ) indexparameters [ WHERE ( predicate ) ] |\nFOREIGN KEY ( columnname [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]\n[ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE referentialaction ] [ ON UPDATE referentialaction ] }\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\nand tableconstraintusingindex is:\n[ CONSTRAINT constraintname ]\n{ UNIQUE | PRIMARY KEY } USING INDEX indexname\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\nindexparameters in UNIQUE, PRIMARY KEY, and EXCLUDE constraints are:\n[ INCLUDE ( columnname [, ... ] ) ]\n[ WITH ( storageparameter [= value] [, ... ] ) ]\n[ USING INDEX TABLESPACE tablespacename ]\nexcludeelement in an EXCLUDE constraint is:\n{ columnname | ( expression ) } [ COLLATE collation ] [ opclass [ ( opclassparameter = value [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]",
    "sections": {
        "NAME": {
            "content": "ALTERTABLE - change the definition of a table\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\naction [, ... ]\nALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\nRENAME [ COLUMN ] columnname TO newcolumnname\nALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]\nRENAME CONSTRAINT constraintname TO newconstraintname\nALTER TABLE [ IF EXISTS ] name\nRENAME TO newname\nALTER TABLE [ IF EXISTS ] name\nSET SCHEMA newschema\nALTER TABLE ALL IN TABLESPACE name [ OWNED BY rolename [, ... ] ]\nSET TABLESPACE newtablespace [ NOWAIT ]\nALTER TABLE [ IF EXISTS ] name\nATTACH PARTITION partitionname { FOR VALUES partitionboundspec | DEFAULT }\nALTER TABLE [ IF EXISTS ] name\nDETACH PARTITION partitionname [ CONCURRENTLY | FINALIZE ]\n\nwhere action is one of:\n\nADD [ COLUMN ] [ IF NOT EXISTS ] columnname datatype [ COLLATE collation ] [ columnconstraint [ ... ] ]\nDROP [ COLUMN ] [ IF EXISTS ] columnname [ RESTRICT | CASCADE ]\nALTER [ COLUMN ] columnname [ SET DATA ] TYPE datatype [ COLLATE collation ] [ USING expression ]\nALTER [ COLUMN ] columnname SET DEFAULT expression\nALTER [ COLUMN ] columnname DROP DEFAULT\nALTER [ COLUMN ] columnname { SET | DROP } NOT NULL\nALTER [ COLUMN ] columnname DROP EXPRESSION [ IF EXISTS ]\nALTER [ COLUMN ] columnname ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequenceoptions ) ]\nALTER [ COLUMN ] columnname { SET GENERATED { ALWAYS | BY DEFAULT } | SET sequenceoption | RESTART [ [ WITH ] restart ] } [...]\nALTER [ COLUMN ] columnname DROP IDENTITY [ IF EXISTS ]\nALTER [ COLUMN ] columnname SET STATISTICS integer\nALTER [ COLUMN ] columnname SET ( attributeoption = value [, ... ] )\nALTER [ COLUMN ] columnname RESET ( attributeoption [, ... ] )\nALTER [ COLUMN ] columnname SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }\nALTER [ COLUMN ] columnname SET COMPRESSION compressionmethod\nADD tableconstraint [ NOT VALID ]\nADD tableconstraintusingindex\nALTER CONSTRAINT constraintname [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\nVALIDATE CONSTRAINT constraintname\nDROP CONSTRAINT [ IF EXISTS ]  constraintname [ RESTRICT | CASCADE ]\nDISABLE TRIGGER [ triggername | ALL | USER ]\nENABLE TRIGGER [ triggername | ALL | USER ]\nENABLE REPLICA TRIGGER triggername\nENABLE ALWAYS TRIGGER triggername\nDISABLE RULE rewriterulename\nENABLE RULE rewriterulename\nENABLE REPLICA RULE rewriterulename\nENABLE ALWAYS RULE rewriterulename\nDISABLE ROW LEVEL SECURITY\nENABLE ROW LEVEL SECURITY\nFORCE ROW LEVEL SECURITY\nNO FORCE ROW LEVEL SECURITY\nCLUSTER ON indexname\nSET WITHOUT CLUSTER\nSET WITHOUT OIDS\nSET TABLESPACE newtablespace\nSET { LOGGED | UNLOGGED }\nSET ( storageparameter [= value] [, ... ] )\nRESET ( storageparameter [, ... ] )\nINHERIT parenttable\nNO INHERIT parenttable\nOF typename\nNOT OF\nOWNER TO { newowner | CURRENTROLE | CURRENTUSER | SESSIONUSER }\nREPLICA IDENTITY { DEFAULT | USING INDEX indexname | FULL | NOTHING }\n\nand partitionboundspec is:\n\nIN ( partitionboundexpr [, ...] ) |\nFROM ( { partitionboundexpr | MINVALUE | MAXVALUE } [, ...] )\nTO ( { partitionboundexpr | MINVALUE | MAXVALUE } [, ...] ) |\nWITH ( MODULUS numericliteral, REMAINDER numericliteral )\n\nand columnconstraint is:\n\n[ CONSTRAINT constraintname ]\n{ NOT NULL |\nNULL |\nCHECK ( expression ) [ NO INHERIT ] |\nDEFAULT defaultexpr |\nGENERATED ALWAYS AS ( generationexpr ) STORED |\nGENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequenceoptions ) ] |\nUNIQUE indexparameters |\nPRIMARY KEY indexparameters |\nREFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]\n[ ON DELETE referentialaction ] [ ON UPDATE referentialaction ] }\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\n\nand tableconstraint is:\n\n[ CONSTRAINT constraintname ]\n{ CHECK ( expression ) [ NO INHERIT ] |\nUNIQUE ( columnname [, ... ] ) indexparameters |\nPRIMARY KEY ( columnname [, ... ] ) indexparameters |\nEXCLUDE [ USING indexmethod ] ( excludeelement WITH operator [, ... ] ) indexparameters [ WHERE ( predicate ) ] |\nFOREIGN KEY ( columnname [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]\n[ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE referentialaction ] [ ON UPDATE referentialaction ] }\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\n\nand tableconstraintusingindex is:\n\n[ CONSTRAINT constraintname ]\n{ UNIQUE | PRIMARY KEY } USING INDEX indexname\n[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\n\nindexparameters in UNIQUE, PRIMARY KEY, and EXCLUDE constraints are:\n\n[ INCLUDE ( columnname [, ... ] ) ]\n[ WITH ( storageparameter [= value] [, ... ] ) ]\n[ USING INDEX TABLESPACE tablespacename ]\n\nexcludeelement in an EXCLUDE constraint is:\n\n{ columnname | ( expression ) } [ COLLATE collation ] [ opclass [ ( opclassparameter = value [, ... ] ) ] ] [ ASC | DESC ] [ NULLS { FIRST | LAST } ]\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "ALTER TABLE changes the definition of an existing table. There are several subforms described\nbelow. Note that the lock level required may differ for each subform. An ACCESS EXCLUSIVE\nlock is acquired unless explicitly noted. When multiple subcommands are given, the lock\nacquired will be the strictest one required by any subcommand.\n\nADD [ COLUMN ] [ IF NOT EXISTS ]\nThis form adds a new column to the table, using the same syntax as CREATE TABLE. If IF\nNOT EXISTS is specified and a column already exists with this name, no error is thrown.\n\nDROP [ COLUMN ] [ IF EXISTS ]\nThis form drops a column from a table. Indexes and table constraints involving the column\nwill be automatically dropped as well. Multivariate statistics referencing the dropped\ncolumn will also be removed if the removal of the column would cause the statistics to\ncontain data for only a single column. You will need to say CASCADE if anything outside\nthe table depends on the column, for example, foreign key references or views. If IF\nEXISTS is specified and the column does not exist, no error is thrown. In this case a\nnotice is issued instead.\n\nSET DATA TYPE\nThis form changes the type of a column of a table. Indexes and simple table constraints\ninvolving the column will be automatically converted to use the new column type by\nreparsing the originally supplied expression. The optional COLLATE clause specifies a\ncollation for the new column; if omitted, the collation is the default for the new column\ntype. The optional USING clause specifies how to compute the new column value from the\nold; if omitted, the default conversion is the same as an assignment cast from old data\ntype to new. A USING clause must be provided if there is no implicit or assignment cast\nfrom old to new type.\n\nSET/DROP DEFAULT\nThese forms set or remove the default value for a column (where removal is equivalent to\nsetting the default value to NULL). The new default value will only apply in subsequent\nINSERT or UPDATE commands; it does not cause rows already in the table to change.\n\nSET/DROP NOT NULL\nThese forms change whether a column is marked to allow null values or to reject null\nvalues.\n\nSET NOT NULL may only be applied to a column provided none of the records in the table\ncontain a NULL value for the column. Ordinarily this is checked during the ALTER TABLE by\nscanning the entire table; however, if a valid CHECK constraint exists (and is not\ndropped in the same command) which proves no NULL can exist, then the table scan is\nskipped.\n\nIf this table is a partition, one cannot perform DROP NOT NULL on a column if it is\nmarked NOT NULL in the parent table. To drop the NOT NULL constraint from all the\npartitions, perform DROP NOT NULL on the parent table. Even if there is no NOT NULL\nconstraint on the parent, such a constraint can still be added to individual partitions,\nif desired; that is, the children can disallow nulls even if the parent allows them, but\nnot the other way around.\n\nDROP EXPRESSION [ IF EXISTS ]\nThis form turns a stored generated column into a normal base column. Existing data in the\ncolumns is retained, but future changes will no longer apply the generation expression.\n\nIf DROP EXPRESSION IF EXISTS is specified and the column is not a stored generated\ncolumn, no error is thrown. In this case a notice is issued instead.\n\nADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY\nSET GENERATED { ALWAYS | BY DEFAULT }\nDROP IDENTITY [ IF EXISTS ]\nThese forms change whether a column is an identity column or change the generation\nattribute of an existing identity column. See CREATE TABLE for details. Like SET DEFAULT,\nthese forms only affect the behavior of subsequent INSERT and UPDATE commands; they do\nnot cause rows already in the table to change.\n\nIf DROP IDENTITY IF EXISTS is specified and the column is not an identity column, no\nerror is thrown. In this case a notice is issued instead.\n\nSET sequenceoption\nRESTART\nThese forms alter the sequence that underlies an existing identity column.\nsequenceoption is an option supported by ALTER SEQUENCE such as INCREMENT BY.\n\nSET STATISTICS\nThis form sets the per-column statistics-gathering target for subsequent ANALYZE\noperations. The target can be set in the range 0 to 10000; alternatively, set it to -1 to\nrevert to using the system default statistics target (defaultstatisticstarget). For\nmore information on the use of statistics by the PostgreSQL query planner, refer to\nSection 14.2.\n\nSET STATISTICS acquires a SHARE UPDATE EXCLUSIVE lock.\n\nSET ( attributeoption = value [, ... ] )\nRESET ( attributeoption [, ... ] )\nThis form sets or resets per-attribute options. Currently, the only defined per-attribute\noptions are ndistinct and ndistinctinherited, which override the\nnumber-of-distinct-values estimates made by subsequent ANALYZE operations.  ndistinct\naffects the statistics for the table itself, while ndistinctinherited affects the\nstatistics gathered for the table plus its inheritance children, and for the statistics\ngathered for partitioned tables. When the value specified is a positive value, the query\nplanner will assume that the column contains exactly the specified number of distinct\nnonnull values. Fractional values may also be specified by using values below 0 and above\nor equal to -1. This instructs the query planner to estimate the number of distinct\nvalues by multiplying the absolute value of the specified number by the estimated number\nof rows in the table. For example, a value of -1 implies that all values in the column\nare distinct, while a value of -0.5 implies that each value appears twice on average.\nThis can be useful when the size of the table changes over time. For more information on\nthe use of statistics by the PostgreSQL query planner, refer to Section 14.2.\n\nChanging per-attribute options acquires a SHARE UPDATE EXCLUSIVE lock.\n\nSET STORAGE\nThis form sets the storage mode for a column. This controls whether this column is held\ninline or in a secondary TOAST table, and whether the data should be compressed or not.\nPLAIN must be used for fixed-length values such as integer and is inline, uncompressed.\nMAIN is for inline, compressible data.  EXTERNAL is for external, uncompressed data, and\nEXTENDED is for external, compressed data.  EXTENDED is the default for most data types\nthat support non-PLAIN storage. Use of EXTERNAL will make substring operations on very\nlarge text and bytea values run faster, at the penalty of increased storage space. Note\nthat SET STORAGE doesn't itself change anything in the table, it just sets the strategy\nto be pursued during future table updates. See Section 70.2 for more information.\n\nSET COMPRESSION compressionmethod\nThis form sets the compression method for a column, determining how values inserted in\nfuture will be compressed (if the storage mode permits compression at all). This does not\ncause the table to be rewritten, so existing data may still be compressed with other\ncompression methods. If the table is restored with pgrestore, then all values are\nrewritten with the configured compression method. However, when data is inserted from\nanother relation (for example, by INSERT ... SELECT), values from the source table are\nnot necessarily detoasted, so any previously compressed data may retain its existing\ncompression method, rather than being recompressed with the compression method of the\ntarget column. The supported compression methods are pglz and lz4. (lz4 is available only\nif --with-lz4 was used when building PostgreSQL.) In addition, compressionmethod can be\ndefault, which selects the default behavior of consulting the defaulttoastcompression\nsetting at the time of data insertion to determine the method to use.\n\nADD tableconstraint [ NOT VALID ]\nThis form adds a new constraint to a table using the same constraint syntax as CREATE\nTABLE, plus the option NOT VALID, which is currently only allowed for foreign key and\nCHECK constraints.\n\nNormally, this form will cause a scan of the table to verify that all existing rows in\nthe table satisfy the new constraint. But if the NOT VALID option is used, this\npotentially-lengthy scan is skipped. The constraint will still be enforced against\nsubsequent inserts or updates (that is, they'll fail unless there is a matching row in\nthe referenced table, in the case of foreign keys, or they'll fail unless the new row\nmatches the specified check condition). But the database will not assume that the\nconstraint holds for all rows in the table, until it is validated by using the VALIDATE\nCONSTRAINT option. See Notes below for more information about using the NOT VALID option.\n\nAlthough most forms of ADD tableconstraint require an ACCESS EXCLUSIVE lock, ADD FOREIGN\nKEY requires only a SHARE ROW EXCLUSIVE lock. Note that ADD FOREIGN KEY also acquires a\nSHARE ROW EXCLUSIVE lock on the referenced table, in addition to the lock on the table on\nwhich the constraint is declared.\n\nAdditional restrictions apply when unique or primary key constraints are added to\npartitioned tables; see CREATE TABLE. Also, foreign key constraints on partitioned tables\nmay not be declared NOT VALID at present.\n\nADD tableconstraintusingindex\nThis form adds a new PRIMARY KEY or UNIQUE constraint to a table based on an existing\nunique index. All the columns of the index will be included in the constraint.\n\nThe index cannot have expression columns nor be a partial index. Also, it must be a\nb-tree index with default sort ordering. These restrictions ensure that the index is\nequivalent to one that would be built by a regular ADD PRIMARY KEY or ADD UNIQUE command.\n\nIf PRIMARY KEY is specified, and the index's columns are not already marked NOT NULL,\nthen this command will attempt to do ALTER COLUMN SET NOT NULL against each such column.\nThat requires a full table scan to verify the column(s) contain no nulls. In all other\ncases, this is a fast operation.\n\nIf a constraint name is provided then the index will be renamed to match the constraint\nname. Otherwise the constraint will be named the same as the index.\n\nAfter this command is executed, the index is “owned” by the constraint, in the same way\nas if the index had been built by a regular ADD PRIMARY KEY or ADD UNIQUE command. In\nparticular, dropping the constraint will make the index disappear too.\n\nThis form is not currently supported on partitioned tables.\n\nNote\nAdding a constraint using an existing index can be helpful in situations where a new\nconstraint needs to be added without blocking table updates for a long time. To do\nthat, create the index using CREATE INDEX CONCURRENTLY, and then install it as an\nofficial constraint using this syntax. See the example below.\n\nALTER CONSTRAINT\nThis form alters the attributes of a constraint that was previously created. Currently\nonly foreign key constraints may be altered.\n\nVALIDATE CONSTRAINT\nThis form validates a foreign key or check constraint that was previously created as NOT\nVALID, by scanning the table to ensure there are no rows for which the constraint is not\nsatisfied. Nothing happens if the constraint is already marked valid. (See Notes below\nfor an explanation of the usefulness of this command.)\n\nThis command acquires a SHARE UPDATE EXCLUSIVE lock.\n\nDROP CONSTRAINT [ IF EXISTS ]\nThis form drops the specified constraint on a table, along with any index underlying the\nconstraint. If IF EXISTS is specified and the constraint does not exist, no error is\nthrown. In this case a notice is issued instead.\n\nDISABLE/ENABLE [ REPLICA | ALWAYS ] TRIGGER\nThese forms configure the firing of trigger(s) belonging to the table. A disabled trigger\nis still known to the system, but is not executed when its triggering event occurs. For a\ndeferred trigger, the enable status is checked when the event occurs, not when the\ntrigger function is actually executed. One can disable or enable a single trigger\nspecified by name, or all triggers on the table, or only user triggers (this option\nexcludes internally generated constraint triggers such as those that are used to\nimplement foreign key constraints or deferrable uniqueness and exclusion constraints).\nDisabling or enabling internally generated constraint triggers requires superuser\nprivileges; it should be done with caution since of course the integrity of the\nconstraint cannot be guaranteed if the triggers are not executed.\n\nThe trigger firing mechanism is also affected by the configuration variable\nsessionreplicationrole. Simply enabled triggers (the default) will fire when the\nreplication role is “origin” (the default) or “local”. Triggers configured as ENABLE\nREPLICA will only fire if the session is in “replica” mode, and triggers configured as\nENABLE ALWAYS will fire regardless of the current replication role.\n\nThe effect of this mechanism is that in the default configuration, triggers do not fire\non replicas. This is useful because if a trigger is used on the origin to propagate data\nbetween tables, then the replication system will also replicate the propagated data, and\nthe trigger should not fire a second time on the replica, because that would lead to\nduplication. However, if a trigger is used for another purpose such as creating external\nalerts, then it might be appropriate to set it to ENABLE ALWAYS so that it is also fired\non replicas.\n\nThis command acquires a SHARE ROW EXCLUSIVE lock.\n\nDISABLE/ENABLE [ REPLICA | ALWAYS ] RULE\nThese forms configure the firing of rewrite rules belonging to the table. A disabled rule\nis still known to the system, but is not applied during query rewriting. The semantics\nare as for disabled/enabled triggers. This configuration is ignored for ON SELECT rules,\nwhich are always applied in order to keep views working even if the current session is in\na non-default replication role.\n\nThe rule firing mechanism is also affected by the configuration variable\nsessionreplicationrole, analogous to triggers as described above.\n\nDISABLE/ENABLE ROW LEVEL SECURITY\nThese forms control the application of row security policies belonging to the table. If\nenabled and no policies exist for the table, then a default-deny policy is applied. Note\nthat policies can exist for a table even if row-level security is disabled. In this case,\nthe policies will not be applied and the policies will be ignored. See also CREATE\nPOLICY.\n\nNO FORCE/FORCE ROW LEVEL SECURITY\nThese forms control the application of row security policies belonging to the table when\nthe user is the table owner. If enabled, row-level security policies will be applied when\nthe user is the table owner. If disabled (the default) then row-level security will not\nbe applied when the user is the table owner. See also CREATE POLICY.\n\nCLUSTER ON\nThis form selects the default index for future CLUSTER operations. It does not actually\nre-cluster the table.\n\nChanging cluster options acquires a SHARE UPDATE EXCLUSIVE lock.\n\nSET WITHOUT CLUSTER\nThis form removes the most recently used CLUSTER index specification from the table. This\naffects future cluster operations that don't specify an index.\n\nChanging cluster options acquires a SHARE UPDATE EXCLUSIVE lock.\n\nSET WITHOUT OIDS\nBackward-compatible syntax for removing the oid system column. As oid system columns\ncannot be added anymore, this never has an effect.\n\nSET TABLESPACE\nThis form changes the table's tablespace to the specified tablespace and moves the data\nfile(s) associated with the table to the new tablespace. Indexes on the table, if any,\nare not moved; but they can be moved separately with additional SET TABLESPACE commands.\nWhen applied to a partitioned table, nothing is moved, but any partitions created\nafterwards with CREATE TABLE PARTITION OF will use that tablespace, unless overridden by\na TABLESPACE clause.\n\nAll tables in the current database in a tablespace can be moved by using the ALL IN\nTABLESPACE form, which will lock all tables to be moved first and then move each one.\nThis form also supports OWNED BY, which will only move tables owned by the roles\nspecified. If the NOWAIT option is specified then the command will fail if it is unable\nto acquire all of the locks required immediately. Note that system catalogs are not moved\nby this command; use ALTER DATABASE or explicit ALTER TABLE invocations instead if\ndesired. The informationschema relations are not considered part of the system catalogs\nand will be moved. See also CREATE TABLESPACE.\n\nSET { LOGGED | UNLOGGED }\nThis form changes the table from unlogged to logged or vice-versa (see UNLOGGED). It\ncannot be applied to a temporary table.\n\nSET ( storageparameter [= value] [, ... ] )\nThis form changes one or more storage parameters for the table. See Storage Parameters in\nthe CREATE TABLE documentation for details on the available parameters. Note that the\ntable contents will not be modified immediately by this command; depending on the\nparameter you might need to rewrite the table to get the desired effects. That can be\ndone with VACUUM FULL, CLUSTER or one of the forms of ALTER TABLE that forces a table\nrewrite. For planner related parameters, changes will take effect from the next time the\ntable is locked so currently executing queries will not be affected.\n\nSHARE UPDATE EXCLUSIVE lock will be taken for fillfactor, toast and autovacuum storage\nparameters, as well as the planner parameter parallelworkers.\n\nRESET ( storageparameter [, ... ] )\nThis form resets one or more storage parameters to their defaults. As with SET, a table\nrewrite might be needed to update the table entirely.\n\nINHERIT parenttable\nThis form adds the target table as a new child of the specified parent table.\nSubsequently, queries against the parent will include records of the target table. To be\nadded as a child, the target table must already contain all the same columns as the\nparent (it could have additional columns, too). The columns must have matching data\ntypes, and if they have NOT NULL constraints in the parent then they must also have NOT\nNULL constraints in the child.\n\nThere must also be matching child-table constraints for all CHECK constraints of the\nparent, except those marked non-inheritable (that is, created with ALTER TABLE ... ADD\nCONSTRAINT ... NO INHERIT) in the parent, which are ignored; all child-table constraints\nmatched must not be marked non-inheritable. Currently UNIQUE, PRIMARY KEY, and FOREIGN\nKEY constraints are not considered, but this might change in the future.\n\nNO INHERIT parenttable\nThis form removes the target table from the list of children of the specified parent\ntable. Queries against the parent table will no longer include records drawn from the\ntarget table.\n\nOF typename\nThis form links the table to a composite type as though CREATE TABLE OF had formed it.\nThe table's list of column names and types must precisely match that of the composite\ntype. The table must not inherit from any other table. These restrictions ensure that\nCREATE TABLE OF would permit an equivalent table definition.\n\nNOT OF\nThis form dissociates a typed table from its type.\n\nOWNER TO\nThis form changes the owner of the table, sequence, view, materialized view, or foreign\ntable to the specified user.\n\nREPLICA IDENTITY\nThis form changes the information which is written to the write-ahead log to identify\nrows which are updated or deleted. In most cases, the old value of each column is only\nlogged if it differs from the new value; however, if the old value is stored externally,\nit is always logged regardless of whether it changed. This option has no effect except\nwhen logical replication is in use.\n\nDEFAULT\nRecords the old values of the columns of the primary key, if any. This is the default\nfor non-system tables.\n\nUSING INDEX indexname\nRecords the old values of the columns covered by the named index, that must be\nunique, not partial, not deferrable, and include only columns marked NOT NULL. If\nthis index is dropped, the behavior is the same as NOTHING.\n\nFULL\nRecords the old values of all columns in the row.\n\nNOTHING\nRecords no information about the old row. This is the default for system tables.\n\n\nRENAME\nThe RENAME forms change the name of a table (or an index, sequence, view, materialized\nview, or foreign table), the name of an individual column in a table, or the name of a\nconstraint of the table. When renaming a constraint that has an underlying index, the\nindex is renamed as well. There is no effect on the stored data.\n\nSET SCHEMA\nThis form moves the table into another schema. Associated indexes, constraints, and\nsequences owned by table columns are moved as well.\n\nATTACH PARTITION partitionname { FOR VALUES partitionboundspec | DEFAULT }\nThis form attaches an existing table (which might itself be partitioned) as a partition\nof the target table. The table can be attached as a partition for specific values using\nFOR VALUES or as a default partition by using DEFAULT. For each index in the target\ntable, a corresponding one will be created in the attached table; or, if an equivalent\nindex already exists, it will be attached to the target table's index, as if ALTER INDEX\nATTACH PARTITION had been executed. Note that if the existing table is a foreign table,\nit is currently not allowed to attach the table as a partition of the target table if\nthere are UNIQUE indexes on the target table. (See also CREATE FOREIGN TABLE\n(CREATEFOREIGNTABLE(7)).) For each user-defined row-level trigger that exists in the\ntarget table, a corresponding one is created in the attached table.\n\nA partition using FOR VALUES uses same syntax for partitionboundspec as CREATE TABLE.\nThe partition bound specification must correspond to the partitioning strategy and\npartition key of the target table. The table to be attached must have all the same\ncolumns as the target table and no more; moreover, the column types must also match.\nAlso, it must have all the NOT NULL and CHECK constraints of the target table, not marked\nNO INHERIT. Currently FOREIGN KEY constraints are not considered.  UNIQUE and PRIMARY KEY\nconstraints from the parent table will be created in the partition, if they don't already\nexist.\n\nIf the new partition is a regular table, a full table scan is performed to check that\nexisting rows in the table do not violate the partition constraint. It is possible to\navoid this scan by adding a valid CHECK constraint to the table that allows only rows\nsatisfying the desired partition constraint before running this command. The CHECK\nconstraint will be used to determine that the table need not be scanned to validate the\npartition constraint. This does not work, however, if any of the partition keys is an\nexpression and the partition does not accept NULL values. If attaching a list partition\nthat will not accept NULL values, also add a NOT NULL constraint to the partition key\ncolumn, unless it's an expression.\n\nIf the new partition is a foreign table, nothing is done to verify that all the rows in\nthe foreign table obey the partition constraint. (See the discussion in CREATE FOREIGN\nTABLE (CREATEFOREIGNTABLE(7)) about constraints on the foreign table.)\n\nWhen a table has a default partition, defining a new partition changes the partition\nconstraint for the default partition. The default partition can't contain any rows that\nwould need to be moved to the new partition, and will be scanned to verify that none are\npresent. This scan, like the scan of the new partition, can be avoided if an appropriate\nCHECK constraint is present. Also like the scan of the new partition, it is always\nskipped when the default partition is a foreign table.\n\nAttaching a partition acquires a SHARE UPDATE EXCLUSIVE lock on the parent table, in\naddition to the ACCESS EXCLUSIVE locks on the table being attached and on the default\npartition (if any).\n\nFurther locks must also be held on all sub-partitions if the table being attached is\nitself a partitioned table. Likewise if the default partition is itself a partitioned\ntable. The locking of the sub-partitions can be avoided by adding a CHECK constraint as\ndescribed in Section 5.11.2.2.\n\nDETACH PARTITION partitionname [ CONCURRENTLY | FINALIZE ]\nThis form detaches the specified partition of the target table. The detached partition\ncontinues to exist as a standalone table, but no longer has any ties to the table from\nwhich it was detached. Any indexes that were attached to the target table's indexes are\ndetached. Any triggers that were created as clones of those in the target table are\nremoved.  SHARE lock is obtained on any tables that reference this partitioned table in\nforeign key constraints.\n\nIf CONCURRENTLY is specified, it runs using a reduced lock level to avoid blocking other\nsessions that might be accessing the partitioned table. In this mode, two transactions\nare used internally. During the first transaction, a SHARE UPDATE EXCLUSIVE lock is taken\non both parent table and partition, and the partition is marked as undergoing detach; at\nthat point, the transaction is committed and all other transactions using the partitioned\ntable are waited for. Once all those transactions have completed, the second transaction\nacquires SHARE UPDATE EXCLUSIVE on the partitioned table and ACCESS EXCLUSIVE on the\npartition, and the detach process completes. A CHECK constraint that duplicates the\npartition constraint is added to the partition.  CONCURRENTLY cannot be run in a\ntransaction block and is not allowed if the partitioned table contains a default\npartition.\n\nIf FINALIZE is specified, a previous DETACH CONCURRENTLY invocation that was canceled or\ninterrupted is completed. At most one partition in a partitioned table can be pending\ndetach at a time.\n\nAll the forms of ALTER TABLE that act on a single table, except RENAME, SET SCHEMA, ATTACH\nPARTITION, and DETACH PARTITION can be combined into a list of multiple alterations to be\napplied together. For example, it is possible to add several columns and/or alter the type of\nseveral columns in a single command. This is particularly useful with large tables, since\nonly one pass over the table need be made.\n\nYou must own the table to use ALTER TABLE. To change the schema or tablespace of a table, you\nmust also have CREATE privilege on the new schema or tablespace. To add the table as a new\nchild of a parent table, you must own the parent table as well. Also, to attach a table as a\nnew partition of the table, you must own the table being attached. To alter the owner, you\nmust also be a direct or indirect member of the new owning role, and that role must have\nCREATE privilege on the table's schema. (These restrictions enforce that altering the owner\ndoesn't do anything you couldn't do by dropping and recreating the table. However, a\nsuperuser can alter ownership of any table anyway.) To add a column or alter a column type or\nuse the OF clause, you must also have USAGE privilege on the data type.\n",
            "subsections": []
        },
        "PARAMETERS": {
            "content": "IF EXISTS\nDo not throw an error if the table does not exist. A notice is issued in this case.\n\nname\nThe name (optionally schema-qualified) of an existing table to alter. If ONLY is\nspecified before the table name, only that table is altered. If ONLY is not specified,\nthe table and all its descendant tables (if any) are altered. Optionally, * can be\nspecified after the table name to explicitly indicate that descendant tables are\nincluded.\n\ncolumnname\nName of a new or existing column.\n\nnewcolumnname\nNew name for an existing column.\n\nnewname\nNew name for the table.\n\ndatatype\nData type of the new column, or new data type for an existing column.\n\ntableconstraint\nNew table constraint for the table.\n\nconstraintname\nName of a new or existing constraint.\n\nCASCADE\nAutomatically drop objects that depend on the dropped column or constraint (for example,\nviews referencing the column), and in turn all objects that depend on those objects (see\nSection 5.14).\n\nRESTRICT\nRefuse to drop the column or constraint if there are any dependent objects. This is the\ndefault behavior.\n\ntriggername\nName of a single trigger to disable or enable.\n\nALL\nDisable or enable all triggers belonging to the table. (This requires superuser privilege\nif any of the triggers are internally generated constraint triggers such as those that\nare used to implement foreign key constraints or deferrable uniqueness and exclusion\nconstraints.)\n\nUSER\nDisable or enable all triggers belonging to the table except for internally generated\nconstraint triggers such as those that are used to implement foreign key constraints or\ndeferrable uniqueness and exclusion constraints.\n\nindexname\nThe name of an existing index.\n\nstorageparameter\nThe name of a table storage parameter.\n\nvalue\nThe new value for a table storage parameter. This might be a number or a word depending\non the parameter.\n\nparenttable\nA parent table to associate or de-associate with this table.\n\nnewowner\nThe user name of the new owner of the table.\n\nnewtablespace\nThe name of the tablespace to which the table will be moved.\n\nnewschema\nThe name of the schema to which the table will be moved.\n\npartitionname\nThe name of the table to attach as a new partition or to detach from this table.\n\npartitionboundspec\nThe partition bound specification for a new partition. Refer to CREATE TABLE\n(CREATETABLE(7)) for more details on the syntax of the same.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "The key word COLUMN is noise and can be omitted.\n\nWhen a column is added with ADD COLUMN and a non-volatile DEFAULT is specified, the default\nis evaluated at the time of the statement and the result stored in the table's metadata. That\nvalue will be used for the column for all existing rows. If no DEFAULT is specified, NULL is\nused. In neither case is a rewrite of the table required.\n\nAdding a column with a volatile DEFAULT or changing the type of an existing column will\nrequire the entire table and its indexes to be rewritten. As an exception, when changing the\ntype of an existing column, if the USING clause does not change the column contents and the\nold type is either binary coercible to the new type or an unconstrained domain over the new\ntype, a table rewrite is not needed; but any indexes on the affected columns must still be\nrebuilt. Table and/or index rebuilds may take a significant amount of time for a large table;\nand will temporarily require as much as double the disk space.\n\nAdding a CHECK or NOT NULL constraint requires scanning the table to verify that existing\nrows meet the constraint, but does not require a table rewrite.\n\nSimilarly, when attaching a new partition it may be scanned to verify that existing rows meet\nthe partition constraint.\n\nThe main reason for providing the option to specify multiple changes in a single ALTER TABLE\nis that multiple table scans or rewrites can thereby be combined into a single pass over the\ntable.\n\nScanning a large table to verify a new foreign key or check constraint can take a long time,\nand other updates to the table are locked out until the ALTER TABLE ADD CONSTRAINT command is\ncommitted. The main purpose of the NOT VALID constraint option is to reduce the impact of\nadding a constraint on concurrent updates. With NOT VALID, the ADD CONSTRAINT command does\nnot scan the table and can be committed immediately. After that, a VALIDATE CONSTRAINT\ncommand can be issued to verify that existing rows satisfy the constraint. The validation\nstep does not need to lock out concurrent updates, since it knows that other transactions\nwill be enforcing the constraint for rows that they insert or update; only pre-existing rows\nneed to be checked. Hence, validation acquires only a SHARE UPDATE EXCLUSIVE lock on the\ntable being altered. (If the constraint is a foreign key then a ROW SHARE lock is also\nrequired on the table referenced by the constraint.) In addition to improving concurrency, it\ncan be useful to use NOT VALID and VALIDATE CONSTRAINT in cases where the table is known to\ncontain pre-existing violations. Once the constraint is in place, no new violations can be\ninserted, and the existing problems can be corrected at leisure until VALIDATE CONSTRAINT\nfinally succeeds.\n\nThe DROP COLUMN form does not physically remove the column, but simply makes it invisible to\nSQL operations. Subsequent insert and update operations in the table will store a null value\nfor the column. Thus, dropping a column is quick but it will not immediately reduce the\non-disk size of your table, as the space occupied by the dropped column is not reclaimed. The\nspace will be reclaimed over time as existing rows are updated.\n\nTo force immediate reclamation of space occupied by a dropped column, you can execute one of\nthe forms of ALTER TABLE that performs a rewrite of the whole table. This results in\nreconstructing each row with the dropped column replaced by a null value.\n\nThe rewriting forms of ALTER TABLE are not MVCC-safe. After a table rewrite, the table will\nappear empty to concurrent transactions, if they are using a snapshot taken before the\nrewrite occurred. See Section 13.5 for more details.\n\nThe USING option of SET DATA TYPE can actually specify any expression involving the old\nvalues of the row; that is, it can refer to other columns as well as the one being converted.\nThis allows very general conversions to be done with the SET DATA TYPE syntax. Because of\nthis flexibility, the USING expression is not applied to the column's default value (if any);\nthe result might not be a constant expression as required for a default. This means that when\nthere is no implicit or assignment cast from old to new type, SET DATA TYPE might fail to\nconvert the default even though a USING clause is supplied. In such cases, drop the default\nwith DROP DEFAULT, perform the ALTER TYPE, and then use SET DEFAULT to add a suitable new\ndefault. Similar considerations apply to indexes and constraints involving the column.\n\nIf a table has any descendant tables, it is not permitted to add, rename, or change the type\nof a column in the parent table without doing the same to the descendants. This ensures that\nthe descendants always have columns matching the parent. Similarly, a CHECK constraint cannot\nbe renamed in the parent without also renaming it in all descendants, so that CHECK\nconstraints also match between the parent and its descendants. (That restriction does not\napply to index-based constraints, however.) Also, because selecting from the parent also\nselects from its descendants, a constraint on the parent cannot be marked valid unless it is\nalso marked valid for those descendants. In all of these cases, ALTER TABLE ONLY will be\nrejected.\n\nA recursive DROP COLUMN operation will remove a descendant table's column only if the\ndescendant does not inherit that column from any other parents and never had an independent\ndefinition of the column. A nonrecursive DROP COLUMN (i.e., ALTER TABLE ONLY ... DROP COLUMN)\nnever removes any descendant columns, but instead marks them as independently defined rather\nthan inherited. A nonrecursive DROP COLUMN command will fail for a partitioned table, because\nall partitions of a table must have the same columns as the partitioning root.\n\nThe actions for identity columns (ADD GENERATED, SET etc., DROP IDENTITY), as well as the\nactions TRIGGER, CLUSTER, OWNER, and TABLESPACE never recurse to descendant tables; that is,\nthey always act as though ONLY were specified. Adding a constraint recurses only for CHECK\nconstraints that are not marked NO INHERIT.\n\nChanging any part of a system catalog table is not permitted.\n\nRefer to CREATE TABLE (CREATETABLE(7)) for a further description of valid parameters.\nChapter 5 has further information on inheritance.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "To add a column of type varchar to a table:\n\nALTER TABLE distributors ADD COLUMN address varchar(30);\n\nThat will cause all existing rows in the table to be filled with null values for the new\ncolumn.\n\nTo add a column with a non-null default:\n\nALTER TABLE measurements\nADD COLUMN mtime timestamp with time zone DEFAULT now();\n\nExisting rows will be filled with the current time as the value of the new column, and then\nnew rows will receive the time of their insertion.\n\nTo add a column and fill it with a value different from the default to be used later:\n\nALTER TABLE transactions\nADD COLUMN status varchar(30) DEFAULT 'old',\nALTER COLUMN status SET default 'current';\n\nExisting rows will be filled with old, but then the default for subsequent commands will be\ncurrent. The effects are the same as if the two sub-commands had been issued in separate\nALTER TABLE commands.\n\nTo drop a column from a table:\n\nALTER TABLE distributors DROP COLUMN address RESTRICT;\n\nTo change the types of two existing columns in one operation:\n\nALTER TABLE distributors\nALTER COLUMN address TYPE varchar(80),\nALTER COLUMN name TYPE varchar(100);\n\nTo change an integer column containing Unix timestamps to timestamp with time zone via a\nUSING clause:\n\nALTER TABLE foo\nALTER COLUMN footimestamp SET DATA TYPE timestamp with time zone\nUSING\ntimestamp with time zone 'epoch' + footimestamp * interval '1 second';\n\nThe same, when the column has a default expression that won't automatically cast to the new\ndata type:\n\nALTER TABLE foo\nALTER COLUMN footimestamp DROP DEFAULT,\nALTER COLUMN footimestamp TYPE timestamp with time zone\nUSING\ntimestamp with time zone 'epoch' + footimestamp * interval '1 second',\nALTER COLUMN footimestamp SET DEFAULT now();\n\nTo rename an existing column:\n\nALTER TABLE distributors RENAME COLUMN address TO city;\n\nTo rename an existing table:\n\nALTER TABLE distributors RENAME TO suppliers;\n\nTo rename an existing constraint:\n\nALTER TABLE distributors RENAME CONSTRAINT zipchk TO zipcheck;\n\nTo add a not-null constraint to a column:\n\nALTER TABLE distributors ALTER COLUMN street SET NOT NULL;\n\nTo remove a not-null constraint from a column:\n\nALTER TABLE distributors ALTER COLUMN street DROP NOT NULL;\n\nTo add a check constraint to a table and all its children:\n\nALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (charlength(zipcode) = 5);\n\nTo add a check constraint only to a table and not to its children:\n\nALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (charlength(zipcode) = 5) NO INHERIT;\n\n(The check constraint will not be inherited by future children, either.)\n\nTo remove a check constraint from a table and all its children:\n\nALTER TABLE distributors DROP CONSTRAINT zipchk;\n\nTo remove a check constraint from one table only:\n\nALTER TABLE ONLY distributors DROP CONSTRAINT zipchk;\n\n(The check constraint remains in place for any child tables.)\n\nTo add a foreign key constraint to a table:\n\nALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);\n\nTo add a foreign key constraint to a table with the least impact on other work:\n\nALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID;\nALTER TABLE distributors VALIDATE CONSTRAINT distfk;\n\nTo add a (multicolumn) unique constraint to a table:\n\nALTER TABLE distributors ADD CONSTRAINT distidzipcodekey UNIQUE (distid, zipcode);\n\nTo add an automatically named primary key constraint to a table, noting that a table can only\never have one primary key:\n\nALTER TABLE distributors ADD PRIMARY KEY (distid);\n\nTo move a table to a different tablespace:\n\nALTER TABLE distributors SET TABLESPACE fasttablespace;\n\nTo move a table to a different schema:\n\nALTER TABLE myschema.distributors SET SCHEMA yourschema;\n\nTo recreate a primary key constraint, without blocking updates while the index is rebuilt:\n\nCREATE UNIQUE INDEX CONCURRENTLY distidtempidx ON distributors (distid);\nALTER TABLE distributors DROP CONSTRAINT distributorspkey,\nADD CONSTRAINT distributorspkey PRIMARY KEY USING INDEX distidtempidx;\n\nTo attach a partition to a range-partitioned table:\n\nALTER TABLE measurement\nATTACH PARTITION measurementy2016m07 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');\n\nTo attach a partition to a list-partitioned table:\n\nALTER TABLE cities\nATTACH PARTITION citiesab FOR VALUES IN ('a', 'b');\n\nTo attach a partition to a hash-partitioned table:\n\nALTER TABLE orders\nATTACH PARTITION ordersp4 FOR VALUES WITH (MODULUS 4, REMAINDER 3);\n\nTo attach a default partition to a partitioned table:\n\nALTER TABLE cities\nATTACH PARTITION citiespartdef DEFAULT;\n\nTo detach a partition from a partitioned table:\n\nALTER TABLE measurement\nDETACH PARTITION measurementy2015m12;\n",
            "subsections": []
        },
        "COMPATIBILITY": {
            "content": "The forms ADD (without USING INDEX), DROP [COLUMN], DROP IDENTITY, RESTART, SET DEFAULT, SET\nDATA TYPE (without USING), SET GENERATED, and SET sequenceoption conform with the SQL\nstandard. The other forms are PostgreSQL extensions of the SQL standard. Also, the ability to\nspecify more than one manipulation in a single ALTER TABLE command is an extension.\n\nALTER TABLE DROP COLUMN can be used to drop the only column of a table, leaving a zero-column\ntable. This is an extension of SQL, which disallows zero-column tables.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "CREATE TABLE (CREATETABLE(7))\n\n\n\nPostgreSQL 14.23                                2026                                  ALTER TABLE(7)",
            "subsections": []
        }
    },
    "summary": "ALTERTABLE - change the definition of a table",
    "flags": [],
    "examples": [
        "To add a column of type varchar to a table:",
        "ALTER TABLE distributors ADD COLUMN address varchar(30);",
        "That will cause all existing rows in the table to be filled with null values for the new",
        "column.",
        "To add a column with a non-null default:",
        "ALTER TABLE measurements",
        "ADD COLUMN mtime timestamp with time zone DEFAULT now();",
        "Existing rows will be filled with the current time as the value of the new column, and then",
        "new rows will receive the time of their insertion.",
        "To add a column and fill it with a value different from the default to be used later:",
        "ALTER TABLE transactions",
        "ADD COLUMN status varchar(30) DEFAULT 'old',",
        "ALTER COLUMN status SET default 'current';",
        "Existing rows will be filled with old, but then the default for subsequent commands will be",
        "current. The effects are the same as if the two sub-commands had been issued in separate",
        "ALTER TABLE commands.",
        "To drop a column from a table:",
        "ALTER TABLE distributors DROP COLUMN address RESTRICT;",
        "To change the types of two existing columns in one operation:",
        "ALTER TABLE distributors",
        "ALTER COLUMN address TYPE varchar(80),",
        "ALTER COLUMN name TYPE varchar(100);",
        "To change an integer column containing Unix timestamps to timestamp with time zone via a",
        "USING clause:",
        "ALTER TABLE foo",
        "ALTER COLUMN footimestamp SET DATA TYPE timestamp with time zone",
        "USING",
        "timestamp with time zone 'epoch' + footimestamp * interval '1 second';",
        "The same, when the column has a default expression that won't automatically cast to the new",
        "data type:",
        "ALTER TABLE foo",
        "ALTER COLUMN footimestamp DROP DEFAULT,",
        "ALTER COLUMN footimestamp TYPE timestamp with time zone",
        "USING",
        "timestamp with time zone 'epoch' + footimestamp * interval '1 second',",
        "ALTER COLUMN footimestamp SET DEFAULT now();",
        "To rename an existing column:",
        "ALTER TABLE distributors RENAME COLUMN address TO city;",
        "To rename an existing table:",
        "ALTER TABLE distributors RENAME TO suppliers;",
        "To rename an existing constraint:",
        "ALTER TABLE distributors RENAME CONSTRAINT zipchk TO zipcheck;",
        "To add a not-null constraint to a column:",
        "ALTER TABLE distributors ALTER COLUMN street SET NOT NULL;",
        "To remove a not-null constraint from a column:",
        "ALTER TABLE distributors ALTER COLUMN street DROP NOT NULL;",
        "To add a check constraint to a table and all its children:",
        "ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (charlength(zipcode) = 5);",
        "To add a check constraint only to a table and not to its children:",
        "ALTER TABLE distributors ADD CONSTRAINT zipchk CHECK (charlength(zipcode) = 5) NO INHERIT;",
        "(The check constraint will not be inherited by future children, either.)",
        "To remove a check constraint from a table and all its children:",
        "ALTER TABLE distributors DROP CONSTRAINT zipchk;",
        "To remove a check constraint from one table only:",
        "ALTER TABLE ONLY distributors DROP CONSTRAINT zipchk;",
        "(The check constraint remains in place for any child tables.)",
        "To add a foreign key constraint to a table:",
        "ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);",
        "To add a foreign key constraint to a table with the least impact on other work:",
        "ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address) NOT VALID;",
        "ALTER TABLE distributors VALIDATE CONSTRAINT distfk;",
        "To add a (multicolumn) unique constraint to a table:",
        "ALTER TABLE distributors ADD CONSTRAINT distidzipcodekey UNIQUE (distid, zipcode);",
        "To add an automatically named primary key constraint to a table, noting that a table can only",
        "ever have one primary key:",
        "ALTER TABLE distributors ADD PRIMARY KEY (distid);",
        "To move a table to a different tablespace:",
        "ALTER TABLE distributors SET TABLESPACE fasttablespace;",
        "To move a table to a different schema:",
        "ALTER TABLE myschema.distributors SET SCHEMA yourschema;",
        "To recreate a primary key constraint, without blocking updates while the index is rebuilt:",
        "CREATE UNIQUE INDEX CONCURRENTLY distidtempidx ON distributors (distid);",
        "ALTER TABLE distributors DROP CONSTRAINT distributorspkey,",
        "ADD CONSTRAINT distributorspkey PRIMARY KEY USING INDEX distidtempidx;",
        "To attach a partition to a range-partitioned table:",
        "ALTER TABLE measurement",
        "ATTACH PARTITION measurementy2016m07 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');",
        "To attach a partition to a list-partitioned table:",
        "ALTER TABLE cities",
        "ATTACH PARTITION citiesab FOR VALUES IN ('a', 'b');",
        "To attach a partition to a hash-partitioned table:",
        "ALTER TABLE orders",
        "ATTACH PARTITION ordersp4 FOR VALUES WITH (MODULUS 4, REMAINDER 3);",
        "To attach a default partition to a partitioned table:",
        "ALTER TABLE cities",
        "ATTACH PARTITION citiespartdef DEFAULT;",
        "To detach a partition from a partitioned table:",
        "ALTER TABLE measurement",
        "DETACH PARTITION measurementy2015m12;"
    ],
    "see_also": [
        {
            "name": "CREATETABLE",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/CREATETABLE/7/json"
        },
        {
            "name": "TABLE",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/TABLE/7/json"
        }
    ]
}