PostgreSQL ADD COLUMN: Add One or More Columns to a Table
Summary: in this tutorial, you will learn how to use the PostgreSQL ADD COLUMN
statement to add one or more columns to an existing table.
Introduction to the PostgreSQL ADD COLUMN statement
To add a new column to an existing table, you use the ALTER TABLE
ADD COLUMN
statement as follows:
In this syntax:
- First, specify the name of the table to which you want to add a new column after the
ALTER TABLE
keyword. - Second, specify the name of the new column as well as its data type and constraint after the
ADD COLUMN
keywords.
When you add a new column to the table, PostgreSQL appends it at the end of the table. PostgreSQL has no option to specify the position of the new column in the table.
To add multiple columns to an existing table, you use multiple ADD COLUMN
clauses in the ALTER TABLE
statement as follows:
PostgreSQL ADD COLUMN statement examples
Let’s take some examples of using the ALTER TABLE...ADD COLUMN
statement.
Creating a sample table
The following CREATE TABLE
statement creates a new table named customers
with two columns: id
and customer_name
:
1) Adding a new column to a table
First, add the phone
column to the customers
table using the ALTER TABLE...ADD COLUMN
statement:
Second, view the customers
table in psql:
Output:
2) Adding multiple columns to a table
First, add the fax
and email
columns to the customers
table:
Second, view the structure of the customers
table in psql
:
Output:
The output shows the fax
and email
columns were added to the customers
table.
3) Adding a column with a NOT NULL constraint to a table that already has data
First, insert data into the customers
table:
Output:
Second, attempt to add the contact_name
column to the customers
table:
PostgreSQL issued an error:
This is because the contact_name
column has the NOT NULL
constraint. When PostgreSQL added the column, this new column received NULL
, which violates the NOT NULL
constraint.
To address this issue, you can follow these steps:
First, add the contact_name
column without the NOT NULL
constraint:
Second, update the values in the contact_name
column.
If you have contact data from other tables, you can update the contact names in the customers
table based on the data from those tables using the update join statement.
Third, modify the contact_name
column to add the NOT NULL
constraint:
Summary
- Use the PostgreSQL
ALTER TABLE...ADD COLUMN
statement to add one or more columns to a table.