PostgreSQL – Add Column to a Table

To add a new column to a table in PostgreSQL, you can use the ALTER TABLE statement with the ADD COLUMN clause. Below is the syntax:

ALTER TABLE table_name
ADD COLUMN column_name data_type [column_constraints];

Where:

  • table_name is the name of the table to which you want to add a new column.
  • column_name is the name of the new column you want to add.
  • data_type is the data type of the new column.
  • column_constraints (optional) are any additional constraints you want to apply to the new column, such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, etc.

Example, to add a new column called “email” of type varchar(255) to a table called “users”, you can use the following SQL:

ALTER TABLE users
ADD COLUMN email varchar(255);

If you want to add a constraint to the new column, you can include it in the statement. For instance, if you want to make the email column unique, you can use the following SQL statement:

ALTER TABLE users
ADD COLUMN email varchar(255) UNIQUE;

Adding a column to a table can be a time-consuming operation, especially if the table has a large number of rows. It is recommended to avoid adding columns to frequently queried tables, and to test the changes on a development environment before applying them to production.

Similar Posts