40

I use timestamp on MySQL 5.x (with PHP) to remember event times. During development I had to update the table with a query that changes something in all columns. The timestamp was then reset to current time.

How can I make timestamp change only on inserts and not on updates or replace?

Michał Perłakowski
  • 80,501
  • 25
  • 149
  • 167
Nir
  • 23,551
  • 25
  • 80
  • 117
  • 1
    A late answer for others who may Google this: if you use a TIMESTAMP when you do manuals edits in your database; or if you have multiple TIMESTAMP columns and do not want to touch all of them; the MySQL manual says to assign the column to itself. You explicitly set the column to its current value (ie. "updated_on = updated_on"), so that it is not changed by the UPDATE. –  Nov 12 '10 at 16:22

3 Answers3

78

Here's all you need to know. In short, though, I think this should do it:

ALTER TABLE `mytable`
CHANGE `mydatefield` `mydatefield`
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Philippe
  • 9,284
  • 3
  • 37
  • 56
Paolo Bergantino
  • 466,948
  • 77
  • 516
  • 433
1
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP

Very good documentation here for time-stamp.

Code Lღver
  • 15,434
  • 16
  • 54
  • 74
user99974
  • 203
  • 2
  • 3
  • 8
  • I may be missing something but my table is (and was) defined this way but still the dates changed. From mysql explain: 'pur_time', 'timestamp', 'NO', '', 'CURRENT_TIMESTAMP', '' – Nir May 03 '09 at 16:34
0

You can use a default value for that field and not include it in the insert or update query.

cherouvim
  • 31,301
  • 15
  • 102
  • 148