tags:

views:

43

answers:

3

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`;
+4  A: 

The obvious solution is the only solution, unfortunately.

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

Daniel Vassallo
Well the new column is actually just to prime the db with default data before a script runs through and changes the data in that column.
Robbie
Can't the script read the data from the source column and updates it in just one pass? (Without having to copy the data first).
Daniel Vassallo
+1  A: 

If you just need a default in there, you can either choose what the default is statically or use a function call.

ALTER TABLE `myResults` ADD `newDate` DATETIME DEFAULT '2010-01-01';

or

ALTER TABLE `myResults` ADD `newDate` DATETIME DEFAULT current_timestamp;
Matt
Unfortunately the default needs to be the value of myDate.
Robbie
For the script to run? If the script is keying off of these then make the default something really far in the past DEFAULT '1800-01-01'.?
Matt
Well, the script only changes some values. Any unchaged should be myDate. It's not a very good script but it's what I have to work with.
Robbie
A: 

Why would your workload ever demand a new datetime column, that duplicates another columns data? This sounds like horrable practice? How about telling us what you're trying to achieve? You can pull a second column with the same data in a few different ways, without actually duplicating the data:

SELECT date1 AS date_old, date1 AS date_new FROM table;

-or-, you can create a view

CREATE VIEW virtual_table AS
    SELECT date1 AS date_old, date1 AS date_new FROM table
;
SELECT * FROM virtual_table;
Evan Carroll
Sorry, I mentioned that this was to prime data for a script to change in the comments of the other answers. I don't actually ever really want them to be the same value unless the script doesn't change them.
Robbie
"prime data for a script to change in the comments of the other answers", still not very clear about what you're talking about.
Evan Carroll