ruk·si

🐘 PostgreSQL
ALTER TABLE

Updated at 2015-05-02 14:31

All statements works in PostgreSQL 9.1+. For more PostgreSQL notes, check out PostgreSQL Guide

Add a new column.

ALTER TABLE distributor
    ADD COLUMN address text;

Remove a column.

ALTER TABLE distributor
    DROP COLUMN address RESTRICT;

Rename a column.

ALTER TABLE distributor
    RENAME COLUMN address TO city;

Modify columns.

ALTER TABLE distributor
    ALTER COLUMN address TYPE text,
    ALTER COLUMN name TYPE text;

Modify a column in table while updating the data.

-- my_timestamp is originall UNIX timestamp integer.
ALTER TABLE distributor
    ALTER COLUMN my_timestamp DROP DEFAULT,
    ALTER COLUMN my_timestamp TYPE timestamp with time zone
    USING
        timestamp with time zone 'epoch' + (my_timestamp * interval '1 second'),
    ALTER COLUMN my_timestamp SET DEFAULT clock_timestamp();

Add constraint to a column.

ALTER TABLE distributor
    ADD CONSTRAINT zip_check CHECK (char_length(zipcode) = 5);

Drop constraint from a column.

ALTER TABLE distributor
    DROP CONSTRAINT zip_check;

Move a table to another schema.

ALTER TABLE my_schema.distributor
    SET SCHEMA your_schema;

Change primary key of a table.

ALTER TABLE distributor ADD PRIMARY KEY (distributor_id);

Sources