Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly add a copy of a column to a MySQL table

Tags:

sql

mysql

I need a fast way duplicate a DATETIME column in a table and give it a new name.

I have a column named myDate in my table called myResults, I need a query to make a new column in the table called newDate which has the exact same data as the myDate column.

Is there a faster way to do this than by doing the obvious 2 step approach of make a new column, and then copying all the data (it's a large table and I'm looking for the fastest approach)?

Obvious solution:

 ALTER TABLE `myResults` ADD `newDate` DATETIME;    UPDATE `myResults` SET `newDate` = `myDate`; 
like image 961
Robbie Avatar asked Feb 02 '10 16:02

Robbie


People also ask

How do I add a column to an existing MySQL table?

Use ADD to add new columns to a table, and DROP to remove existing columns. DROP col_name is a MySQL extension to standard SQL. To add a column at a specific position within a table row, use FIRST or AFTER col_name . The default is to add the column last.

How do I make a copy of a column in SQL?

You can just add the new column to the table as nullable, either with SQL Server Management Studio by right clicking on the Table and clicking "Design" or by using an ALTER TABLE statement like this ALTER TABLE TableName ADD NewColumnName DataType NULL . J.D. Save this answer.

How do I add multiple columns to an existing table in MySQL?

In MySQL, to add a new column to an existing table, the ALTER TABLE syntax would look like this: ALTER TABLE table_name ADD COLUMN column_name column_definition; Let's try adding multiple columns in one command.


2 Answers

UPDATE `table_name` SET `new_column` = `existing_column` WHERE `id`=`id` 
like image 142
Basharat Ali Avatar answered Oct 02 '22 12:10

Basharat Ali


The obvious solution is the only solution, unfortunately.

However note that in general you shouldn't be copying a column in relational databases.

like image 41
Daniel Vassallo Avatar answered Oct 02 '22 12:10

Daniel Vassallo