views:

42

answers:

4

I am creating some tables where I want to store the time when a record was created and when it was last updated. I thought I could have two timestamp fields where one would have the value CURRENT_TIMESTAMP and the other would have CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. But I guess I can't do this because you can have only 1 timestamp field with a default value in a table?

How would you recommend I get and store the two times? Thanks!

+1  A: 

As far as I know, there's no workaround for that restriction. You'll need to manually set (at least) one of the timestamps, the easiest way is just add updated = NOW() to the UPDATE-query.

GuidoH
+1 That does seem like a workable solution. I would have really loved it, if the server could do it automatically :)
aip.cd.aish
Could be possible with triggers though, but I think that's not a great solution.
GuidoH
+1  A: 

You can have two columns of type timestamp in one table.

The following works for MySQL 5.0

create table t 
(
  id integer, 
  created_at timestamp default current_timestamp, 
  updated_at timestamp
);

I think you are confusing this with SQL Server (where timestamp is not really a "time stamp" and there is indeed a limit on a single "timestamp" column)

Edit: But you will need a trigger to update the update_at column each time the row is changed.

a_horse_with_no_name
That is correct, SQL Server's timestamp is really just a synonym for rowversion
SQLMenace
This would execute, but the updated_at field doesn't get autoupdated on change. I thought adding the ON UPDATE CURRENT_TIMESTAMP on the updated_at column would take care of that. That is when it complains that this cannot be done.
aip.cd.aish
Yes, as I said: you need to use a trigger to populate the updated_at column
a_horse_with_no_name
A: 

You'll need two columns: CREATE_TIME and UPDATE_TIME.

You might want to add CREATE_USER and UPDATE_USER.

Perhaps you'd want to have a 1:many relationship with name of column changed, old and new values.

It's all part of change data capture. You could have CDC tables that are updated using triggers.

duffymo
I do have 2 columns to store create time and update time - but I can't set the two default values I indicated above. I will look into what is CDC. Shouldn't there be a simple solution to this? I'd image this is a common scenario.
aip.cd.aish
It is common, but I don't believe that MySQL has a built-in solution for it. Oracle and SQL Server do. Shouldn't be hard to do: a few tables and triggers.
duffymo
A: 

I would leave the current timestamp the way you suggested and fill in the created_at field with current date on insert.

silvo