Add new column to a table based on calculation

Here are a few ways to add a new column to a table based on a calculation, depending on the database management system you're using:

SQL Server

You can use the ALTER TABLE statement with the ADD clause to add a new column, and then use the UPDATE statement to populate the new column with the calculated value.

For example:

ALTER TABLE mytable
ADD newcolumn AS (oldcolumn * 2);

UPDATE mytable
SET newcolumn = (oldcolumn * 2);

MySQL

You can use the ALTER TABLE statement with the ADD clause to add a new column, and then use the UPDATE statement to populate the new column with the calculated value.

For example:

ALTER TABLE mytable
ADD newcolumn INT;

UPDATE mytable
SET newcolumn = oldcolumn * 2;

PostgreSQL

You can use the ALTER TABLE statement with the ADD clause to add a new column, and then use the UPDATE statement to populate the new column with the calculated value.

For example:

ALTER TABLE mytable
ADD COLUMN newcolumn INT;

UPDATE mytable
SET newcolumn = oldcolumn * 2;

Oracle

You can use the ALTER TABLE statement with the ADD clause to add a new column, and then use the UPDATE statement to populate the new column with the calculated value.

For example:

ALTER TABLE mytable
ADD (newcolumn NUMBER(10));

UPDATE mytable
SET newcolumn = oldcolumn * 2;

SQLite

You can use the ALTER TABLE statement with the ADD clause to add a new column, and then use the UPDATE statement to populate the new column with the calculated value.

For example:

ALTER TABLE mytable
ADD COLUMN newcolumn INTEGER;

UPDATE mytable
SET newcolumn = oldcolumn * 2;

Note that in all cases, you'll need to replace mytable with the actual name of your table, and oldcolumn and newcolumn with the actual names of the columns you're working with.