PostgreSQL

PostgreSQL ADD COLUMN

Add a new column to an existing PostgreSQL table with the ALTER TABLE statement.

Before you begin: Make sure the products table exists and connect to the database in pgAdmin 4's Query Tool.

The ALTER TABLE statement

To add a column to an existing table, use the ALTER TABLE statement. It can also be used to delete or modify columns and to add or remove constraints from an existing table.

ADD COLUMN

We will add a column named color to the products table. When adding a column, specify its data type. The VARCHAR(255) type stores text with a maximum length of 255 characters.

ALTER TABLE products
ADD COLUMN color VARCHAR(255);

ALTER TABLE products identifies the table to change, ADD COLUMN color gives the new column its name, and VARCHAR(255) defines the kind of data it can store.

Result

After you execute the statement, PostgreSQL reports:

ALTER TABLE

This confirms that the table structure was changed successfully.

Display the table

To check the result, use a SELECT statement:

SELECT * FROM products;

The query displays all rows and columns in products. The new color column will appear in the result. Existing rows contain NULL in this column until a color is assigned.

Remember: ALTER TABLE changes the table structure. Test schema changes before applying them to production databases.

Further Reading

Continue learning with these related tutorials:

Continue learning