Skip to main content

ALTER TABLE

The ALTER TABLE statement changes the schema of an existing table in the catalog.

RENAME TABLE​

SQL
ALTER TABLE integersRENAME TO integers_old;

The RENAME TO clause renames an entire table, changing its name in the schema. Indexes follow the rename, except in an attached DuckDB file, where a table that has an index can't be renamed. Views, functions, foreign keys and trigger bodies that refer to the table follow the new name, and the table's own triggers keep firing on it.

SET SCHEMA​

SQL
ALTER TABLE integersSET SCHEMA archive;
SELECT i, j FROM archive.integers ORDER BY i;
 i | j
---+----
 1 | 10
 2 | 20

The SET SCHEMA clause moves a table into another schema, keeping its rows, together with its indexes, its triggers and the sequences it owns, such as those of its SERIAL columns. ALTER TABLE ... SET SCHEMA also moves a view or a sequence; given an index, it fails with cannot change schema of index. The target schema must exist, must not be a system schema such as pg_catalog, and must not already hold a relation of that name, and moving a table needs the CREATE privilege on the target schema. Moving a table into the schema it is already in changes nothing. Views, functions, column defaults, foreign keys and trigger bodies that refer to the moved table, view or sequence follow it into the new schema. A table whose CHECK constraint, DEFAULT or generated column calls a function of its own schema by its name alone can't be moved: the statement fails with Cannot move table "<table>" to schema "<schema>": its expressions call function "<name>", which would resolve to a different function there. The same holds for a sequence of the table's schema that the table doesn't own, named by its name alone as in nextval('order_ids'): the statement fails with Cannot move table "<table>" to schema "<schema>": its expressions use sequence "<name>", which would resolve to a different sequence there. ALTER VIEW and ALTER SEQUENCE move views and sequences, and ALTER TYPE, ALTER FUNCTION and ALTER TEXT SEARCH DICTIONARY move types, functions and dictionaries; a sequence that a table owns moves only with its table, and an index always stays in its table's schema.

RENAME COLUMN​

To rename a column of a table, use the RENAME or RENAME COLUMN clauses:

SQL
ALTER TABLE integersRENAME COLUMN i TO j;
SQL
ALTER TABLE integersRENAME i TO j;

The RENAME [COLUMN] clause renames a single column within a table. Constraints and indexes that use the column are updated automatically; in an attached DuckDB file, a table that has an index can't rename its columns. Views, table functions and triggers that read the column follow the new name, and so does a trigger's UPDATE OF list. A rename that a dependent can't follow unambiguously, such as one of a column that a NATURAL or USING join merges, fails with cannot rename column ⟨name⟩ of table ⟨table⟩ because other objects depend on it and names the dependent.

ADD COLUMN​

To add a column of a table, use the ADD or ADD COLUMN clauses.

E.g., to add a new column with name k to the table integers, it will be filled with the default value NULL:

SQL
ALTER TABLE integersADD COLUMN k INTEGER;

Or:

SQL
ALTER TABLE integersADD k INTEGER;

Add a new column with name l to the table integers, it will be filled with the default value 10:

SQL
ALTER TABLE integersADD COLUMN l INTEGER DEFAULT 10;

The ADD [COLUMN] clause can be used to add a new column of a specified type to a table. The new column will be filled with the specified default value, or NULL if none is specified. Besides DEFAULT, the new column can declare UNIQUE or PRIMARY KEY, and the constraint is enforced from the start. A PRIMARY KEY is also checked against the rows already in the table, which all get the default value: adding id INT DEFAULT 5 PRIMARY KEY to a table of two rows fails because the key contains duplicates. An inline CHECK constraint and a named constraint (CONSTRAINT ⟨name⟩ UNIQUE) are not supported; add them with ADD CONSTRAINT, and NOT NULL with ALTER COLUMN ... SET NOT NULL, in a separate ALTER TABLE step.

A serial column gets a sequence of its own, every row already in the table gets a number from it, and new rows continue from there:

SQL
ALTER TABLE tickets ADD COLUMN id SERIAL;
INSERT INTO tickets (title) VALUES ('third');
SELECT id, titleFROM ticketsORDER BY id;
SELECT pg_get_serial_sequence('tickets', 'id') AS sequence;
 id | title
----+--------
  1 | first
  2 | second
  3 | third

 sequence
-----------------------
 public.tickets_id_seq

With IF NOT EXISTS, adding a serial column that already exists changes nothing and creates no sequence. A serial column can declare PRIMARY KEY or UNIQUE in the same statement, also on a table that already has rows.

DROP COLUMN​

To drop a column of a table, use the DROP or DROP COLUMN clause:

E.g., to drop the column k from the table integers:

SQL
ALTER TABLE integersDROP COLUMN k;

Or:

SQL
ALTER TABLE integersDROP k;

The DROP [COLUMN] clause can be used to remove a column from a table. As in PostgreSQL, every index created with CREATE INDEX that uses the column (as a key, in an indexed expression or in its WHERE predicate) is dropped along with it, and so are the CHECK and FOREIGN KEY constraints of the table that use it (see Schema changes on an indexed table). A column of a PRIMARY KEY or UNIQUE constraint cannot be removed: the statement fails with Cannot drop column ⟨name⟩ because there is a PRIMARY KEY constraint that depends on it, or UNIQUE for a unique constraint; drop the constraint first with DROP CONSTRAINT. In an attached DuckDB file, a column also cannot be removed while an index uses a column that comes after it. A column that a view, a table function or a trigger reads, a trigger's UPDATE OF list included, can't be dropped: the statement fails with cannot drop column ⟨name⟩ of table ⟨table⟩ because other objects depend on it and lists them, and DROP COLUMN ... CASCADE drops those dependents too.

[SET [DATA]] TYPE​

Change the type of the column i to the type VARCHAR using a standard cast:

SQL
ALTER TABLE integersALTER i TYPE VARCHAR;

Change the type of the column i to the type VARCHAR, using the specified expression to convert the data for each row:

SQL
ALTER TABLE integersALTER i SET DATA TYPE VARCHAR USING concat(i, '_', j);

The [SET [DATA]] TYPE clause changes the type of a column in a table. Any data present in the column is converted according to the provided expression in the USING clause, or, if the USING clause is absent, cast to the new data type. Note that a column can only have its type changed if no index and no CHECK, UNIQUE, PRIMARY KEY or FOREIGN KEY constraint uses it.

Handling Structs​

There are two options to change the sub-schema of a STRUCT-typed column.

ALTER TABLE with struct_insert​

You can add fields to a STRUCT column with ALTER TABLE: give the new struct type in the TYPE clause and use struct_insert in the USING clause to transform the existing values. For example:

SQL
CREATE TABLE tbl (col STRUCT(i INTEGER));
INSERT INTO tbl VALUES ({'i': 1});
ALTER TABLE tblALTER col TYPE STRUCT(i INTEGER, a INTEGER, b VARCHAR)USING struct_insert(col, a := 42, b := NULL::VARCHAR);
SELECT col FROM tbl;
 col
---------
 (1,42,)

ALTER TABLE with ADD COLUMN / DROP COLUMN / RENAME COLUMN​

SereneDB ALTER TABLE supports the ADD COLUMN, DROP COLUMN and RENAME COLUMN clauses to update the sub-schema of a STRUCT.

SET / DROP DEFAULT​

The SET DEFAULT clause changes the default value of a column:

SQL
ALTER TABLE integersALTER COLUMN i SET DEFAULT 10;

The DROP DEFAULT clause removes the default value of a column, resetting it to NULL:

SQL
ALTER TABLE integersALTER COLUMN i DROP DEFAULT;

ADD PRIMARY KEY​

The ADD PRIMARY KEY clause promotes one or more existing columns to the table's primary key. The chosen columns are made implicitly NOT NULL, and the constraint is enforced from that point on:

SQL
ALTER TABLE integersADD PRIMARY KEY (i);

A primary key can also span multiple columns:

SQL
ALTER TABLE integersADD PRIMARY KEY (i, j);

The statement fails if the table already has a primary key (table "⟨name⟩" can have only one primary key), or if the existing rows would violate the new constraint: duplicates fail with could not create unique index "⟨name⟩_pkey", and NULL values with column "⟨column⟩" of relation "⟨name⟩" contains null values. A table with indexes takes a primary key like any other.

SET / RESET (Table Options)​

SET (option = value, …) changes the background maintenance options of a table, and RESET (option, …) returns them to the current session defaults. These options can be changed: compaction_interval, compaction_max_segments, compaction_max_segments_bytes and compaction_floor_segment_bytes (see Background compaction). A change reaches the table's background tasks at once and is undone if its transaction rolls back. row_group_size, block_size, segment_memory_max and optimize_top_k are fixed at CREATE TABLE: setting or resetting one fails with option "⟨name⟩" cannot be changed with ALTER TABLE. pg_class.reloptions lists the options whose values differ from the defaults.

SQL
ALTER TABLE events SET (compaction_interval = 0);
ALTER TABLE events RESET (compaction_interval);

An option that doesn't exist is an error:

SQL
ALTER TABLE my_tableSET ('option_name' = 'value');
db error: ERROR: unrecognized parameter "option_name"
SQL
ALTER TABLE my_tableRESET ('option_name');
db error: ERROR: unrecognized parameter "option_name"

A statement that sets or resets several options fails as a whole when one of them doesn't exist:

SQL
ALTER TABLE my_tableSET ('option1' = 'value1', 'option2' = 'value2');
ALTER TABLE my_tableRESET ('option1', 'option2');
db error: ERROR: unrecognized parameter "option1"

db error: ERROR: unrecognized parameter "option1"

SET TABLESPACE, on a table or an index, is not supported and fails with SET TABLESPACE is not supported.

DROP CONSTRAINT​

The DROP CONSTRAINT clause removes a named constraint from a table, a CHECK, UNIQUE, PRIMARY KEY or FOREIGN KEY constraint alike:

SQL
ALTER TABLE itemsDROP CONSTRAINT positive_id;

A PRIMARY KEY or UNIQUE constraint that a foreign key references can't be dropped: the statement fails with cannot drop constraint ⟨name⟩ on table ⟨table⟩ because other objects depend on it. DROP CONSTRAINT ... CASCADE drops the referencing foreign keys too. RENAME CONSTRAINT renames a constraint.

ADD CONSTRAINT​

The ADD CONSTRAINT clause adds a CHECK, UNIQUE, PRIMARY KEY or FOREIGN KEY constraint to an existing table:

SQL
ALTER TABLE itemsADD CONSTRAINT positive_id CHECK (id > 0);

The rows already in the table are checked against the new constraint: a duplicate key fails the statement with could not create unique index "⟨name⟩", and a foreign key value missing from the referenced table with the error an INSERT of that row would raise.

ALTER COLUMN ... SET COMPRESSION​

SET COMPRESSION codec, optionally with (compression_level = N), changes the codec a column is written with, as USING COMPRESSION sets it in CREATE TABLE; SET COMPRESSION DEFAULT returns the column to automatic selection. The same codecs and levels are accepted as at creation (see Columnstore Storage & Compression): the codec has to store the column's type, and only a codec that has levels takes one. A generated column takes a codec only when it is STORED.

SQL
ALTER TABLE events ALTER COLUMN msg SET COMPRESSION dict_zstd(compression_level = 9);
ALTER TABLE events ALTER COLUMN level SET COMPRESSION rle;
ALTER TABLE events ALTER COLUMN msg SET COMPRESSION DEFAULT;

The change applies to the segments written after it and is undone if its transaction rolls back; an older segment keeps its codec until a compaction includes it, which rewrites the column with the named codec and level. A codec that an inverted index names for the column through INCLUDE keeps precedence while that index exists. In a database file with a DuckDB storage version it fails at commit, since such a file holds only what DuckDB reads (see DuckDB files).

ENABLE / DISABLE TRIGGER​

DISABLE TRIGGER name stops a trigger of the table from firing, and ENABLE TRIGGER name lets it fire again. With ALL or USER instead of a name the change applies to every trigger of the table. Like in PostgreSQL, a trigger can also be enabled for a replication role: ENABLE REPLICA TRIGGER makes it fire only in sessions where session_replication_role is replica, such as the apply worker of a subscription, and ENABLE ALWAYS TRIGGER makes it fire in every session. A plain ENABLE TRIGGER trigger fires when the role is origin (the default) or local. pg_trigger.tgenabled shows the state as O, D, R or A. The change is transactional.

SQL
ALTER TABLE orders DISABLE TRIGGER orders_audited;
ALTER TABLE orders ENABLE ALWAYS TRIGGER orders_audited;
SELECT tgname, tgenabled FROM pg_trigger WHERE tgrelid = 'orders'::regclass;
 tgname         | tgenabled
----------------+-----------
 orders_audited | A

Foreign keys are not triggers in SereneDB, so DISABLE TRIGGER ALL does not turn off foreign key checks; a session with session_replication_role set to replica skips them.

Rewrites and concurrent changes​

Renaming the table or a column, ALTER COLUMN SET DEFAULT / DROP DEFAULT, DROP NOT NULL, DROP CONSTRAINT and RENAME CONSTRAINT of a CHECK or NOT NULL constraint, and COMMENT ON COLUMN change only the table's definition.

ADD COLUMN without a default, or with DEFAULT NULL, gives the existing rows NULL. With any other default, the existing rows get the default, evaluated per row, and the statement rewrites the table. A generated column can't be added.

DROP COLUMN drops the indexes on the column and the CHECK and FOREIGN KEY constraints that use it. A column of a PRIMARY KEY or UNIQUE constraint can't be dropped.

ALTER COLUMN TYPE rewrites the table, converting each value with the USING expression, or with a cast when there is none. It is refused for a column of a PRIMARY KEY, UNIQUE or FOREIGN KEY constraint, a column an index covers, a column a CHECK constraint or a generated column uses, and a generated column. If the column is NOT NULL, every converted value must be non-NULL.

Every row written is checked against the NOT NULL and CHECK constraints. SET NOT NULL and adding a CHECK constraint fail if a row of the table violates the new constraint.

ADD COLUMN, DROP COLUMN, ALTER COLUMN TYPE, SET NOT NULL, adding a CHECK, UNIQUE, PRIMARY KEY or FOREIGN KEY constraint and dropping a UNIQUE, PRIMARY KEY or FOREIGN KEY constraint don't wait for the other transactions that wrote to the table; they wait only for a commit of the table that is already under way. Another transaction that wrote to the table fails at COMMIT with table "<name>" was altered by a concurrent transaction (SQLSTATE 40001), unless the ALTER TABLE rolled back first; retry the transaction. While such an ALTER TABLE is uncommitted, and in transactions whose snapshot predates its commit, INSERT and UPDATE of the table fail with the same error. An ALTER TABLE holds the table until its transaction ends, like a change of its indexes; see Concurrent changes. An ALTER TABLE that rewrites the table waits for the table's running compactions and holds off new ones the way CREATE INDEX does.