How to add column with default value in PostgreSQL?

by dalton_moen , in category: PHP Databases , 8 months ago

How to add column with default value in PostgreSQL?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 3 months ago

@dalton_moen 

To add a column with a default value in PostgreSQL, you can use the ALTER TABLE statement with the ADD COLUMN syntax. Here's an example:

1
2
ALTER TABLE table_name
ADD COLUMN column_name data_type DEFAULT default_value;


Replace table_name with the name of the table that you want to modify, column_name with the name of the new column, data_type with the data type of the new column, and default_value with the default value that you want to use.


For example, to add a column named status with a default value of 'active' to a table named users, you can use the following SQL statement:

1
2
ALTER TABLE users
ADD COLUMN status text DEFAULT 'active';


This will add the status column to the users table, and set the default value to 'active' for any rows that are inserted into the table in the future.