Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add MySQL table column with a default value of another column of the existing row

The current existing table looks like this:

id    number    amount    
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00

Now i would like add new column allocated_amount with the default value of the amount column in every existing row.

id    number    amount      allocated_amount  
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00

It is possible? Im using MySQL Workbench GUI.

like image 643
Roel Avatar asked Dec 06 '17 02:12

Roel


People also ask

How do you add a new column to an existing column in MySQL?

Syntax. The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name.

How do you set a column to default value in MySQL?

Try this: ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0; From the documentation that you linked to: ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name alter_specification [, alter_specification] ...


1 Answers

It is not possible as default column. You can write a trigger and do that or add virtual column in Mysql 5.7.

OR

alter table Tab1 add allocated_amount int;  -- Add column
update Tab1 set allocated_amount= amount;   -- Set the value

Or you could create a Virtual Column:

alter table Table1 
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;
like image 164
Sohan.Choudhury Avatar answered Sep 22 '22 16:09

Sohan.Choudhury