How to add column with default value in PostgreSQL?

by dalton_moen , in category: PHP Databases , 2 years ago

How to add column with default value in PostgreSQL?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raphael_tillman , a year 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.

by filiberto , a year ago

@dalton_moen 

To add a column with a default value in PostgreSQL, you can use the ALTER TABLE statement along with the ADD COLUMN clause.


Here is the syntax to add a column with a default value:

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


Explanation of the syntax:

  • ALTER TABLE - The command to modify an existing table.
  • table_name - The name of the table to which you want to add a column.
  • ADD COLUMN - The clause to indicate that you are adding a new column.
  • column_name - The name of the column you want to add.
  • data_type - The data type of the new column.
  • DEFAULT default_value - The clause to specify the default value for the column.


Example:


Let's assume we have a table named "employees" with columns "id" and "name", and we want to add a new column "age" with the default value of 25. The SQL statement to add the column would be:

1
2
ALTER TABLE employees
ADD COLUMN age INT DEFAULT 25;


This will add a new column named "age" of type integer with a default value of 25 to the "employees" table.