Sumit Garg
Sumit Garg

Reputation:

How do you assign a column default in MySQL to another column's value?

I want to add a new column to a table in MySQL database that should get the value of another column in the same table. Is this possible? If so, how do you do it?

Upvotes: 6

Views: 7177

Answers (4)

Md. Maruf Hossain
Md. Maruf Hossain

Reputation: 922

You Can use this following two command to do your work.

  1. This command will be used to add new column in you table. Remember data type from where you want to copy to use those data type in new Column.

    ALTER TABLE table_name ADD new_column_name VARCHAR(60);
    

2: This command to copy data from old column name to new column name.

   UPDATE table_name SET new_column_name = old_column_name;

Then if you want to delete previous column, Then you can use following command

   ALTER TABLE table_name DROP COLUMN old_column_name;

Upvotes: 3

Saam Barrager
Saam Barrager

Reputation: 31

As of 20101212 mysql does not support defaulting 2 timestamp columns, which means you can't do a 'created' and 'updated' on the same table.

If this is what you were trying to do, then the trigger with the stored proc is the way to go.

Upvotes: 2

Ben
Ben

Reputation: 11

create a view, and you can select the same column twice and give it different name, then the application can use the view instead use the table directly.

Upvotes: 1

Alnitak
Alnitak

Reputation: 340055

Starting with MySQL 5.0.2 you can write a stored procedure linked to a TRIGGER which can examine the new column each time a row is inserted, and automatically copy the other column's value into the new column if no value was supplied for the new column.

Upvotes: 6

Related Questions