Add Column in PostgreSql
In PostgreSQL, you can add a new column to an existing table using the ALTER TABLE statement with the ADD COLUMN clause. Here's the basic syntax:
ALTER TABLE table_nameADD COLUMN column_name data_type [constraints];
Parameters:
table_name: The name of the table to which you want to add the column.column_name: The name of the new column.data_type: The data type of the new column (e.g.,INTEGER,VARCHAR(50),TEXT,DATE, etc.).constraints: Optional constraints for the column (e.g.,NOT NULL,DEFAULT value,UNIQUE, etc.).
Examples:
Add a simple column without constraints:
ALTER TABLE employeesADD COLUMN email VARCHAR(100);
Add a column with a
NOT NULLconstraint:ALTER TABLE employees ADD COLUMN hire_date DATE NOT NULL;
Add a column with a default value:
ALTER TABLE employees ADD COLUMN salary NUMERIC(10, 2) DEFAULT 0.00;
Add a column with multiple constraints:
ALTERTABLE employees ADDCOLUMN phone_number VARCHAR(15)NOTNULLUNIQUE;
Add a column with a foreign key constraint:
ALTERTABLE orders ADDCOLUMN customer_id INTREFERENCES customers(id);
Notes:
If you add a column with a
NOT NULLconstraint, you must either provide aDEFAULTvalue or ensure the table is empty, otherwise PostgreSQL will throw an error.You can add multiple columns in a single
ALTER TABLEstatement by separating them with commas:ALTERTABLE employeesADDCOLUMN email VARCHAR(100),ADDCOLUMN hire_date DATENOTNULL,ADDCOLUMN salary NUMERIC(10,2)DEFAULT0.00;
This is how you can add columns to an existing table in PostgreSQL.