PostgreSQL ALTER TABLE
Summary: in this tutorial, you will learn how to use the PostgreSQL ALTER TABLE
statement to modify the structure of a table.
Introduction to PostgreSQL ALTER TABLE statement
To change the structure of an existing table, you use PostgreSQL ALTER TABLE
statement.
The following illustrates the basic syntax of the ALTER TABLE
statement:
PostgreSQL provides you with many actions:
- Add a column
- Drop a column
- Change the data type of a column
- Rename a column
- Set a default value for the column
- Add a constraint to a column.
- Rename a table
To add a new column to a table, you use ALTER TABLE ADD COLUMN
statement:
To drop a column from a table, you use ALTER TABLE DROP COLUMN
statement:
To rename a column, you use the [ALTER TABLE RENAME COLUMN](postgresql-rename-column) TO
statement:
To change a default value of the column, you use ALTER TABLE ALTER COLUMN SET DEFAULT
or DROP DEFAULT
:
To change the NOT NULL
constraint, you use ALTER TABLE ALTER COLUMN
statement:
To add a CHECK
constraint, you use ALTER TABLE ADD CHECK
statement:
Generally, to add a constraint to a table, you use ALTER TABLE ADD CONSTRAINT
statement:
To rename a table you use ALTER TABLE RENAME TO
statement:
PostgreSQL ALTER TABLE examples
Let’s create a new table called links
for practicing with the ALTER TABLE
statement.
To add a new column named active
, you use the following statement:
The following statement removes the active
column from the links
table:
To change the name of the title
column to link_title
, you use the following statement:
The following statement adds a new column named target
to the links
table:
To set _blank
as the default value for the target
column in the links
table, you use the following statement:
If you insert the new row into the links
table without specifying a value for the target
column, the target
column will take the _blank
as the default value. For example:
The following statement selects data from the links
table:
The following statement adds a CHECK
condition to the target
column so that the target
column only accepts the following values: _self
, _blank
, _parent
, and _top
:
If you attempt to insert a new row that violates the CHECK
constraint set for the target
column, PostgreSQL will issue an error as shown in the following example:
The following statement adds a UNIQUE
constraint to the url
column of the links
table:
The following statement attempts to insert the url that already exists:
It causes an error due to the unique_url constraint:
The following statement changes the name of the links
table to urls
:
In this tutorial, you have learned how to use the PostgreSQL ALTER TABLE
statement to change the structure of an existing table.