Skip to Main Content
MySQL Cookbook
book

MySQL Cookbook

by Paul DuBois
October 2002
Intermediate to advanced content levelIntermediate to advanced
1024 pages
27h 26m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook

Recording a Row’s Creation Time

Problem

You want to record the time when a record was created, which TIMESTAMP will do, but you want that time not to change when the record is changed, and a TIMESTAMP cannot hold its value.

Solution

Actually, it can; you just need to include a second TIMESTAMP column, which has different properties than the first.

Discussion

If you want a column to be set initially to the time at which a record is created, but remain constant thereafter, a single TIMESTAMP is not the solution, because it will be updated whenever other columns in the record are updated. Instead, use two TIMESTAMP columns and take advantage of the fact that the second one won’t have the same special properties of the first. Both columns can be set to the current date and time when the record is created. Thereafter, whenever you modify other columns in the record, the first TIMESTAMP column will be updated automatically to reflect the time of the change, but the second remains set to the record creation time. You can see how this works using the following table:

CREATE TABLE tsdemo2
(
    t_update    TIMESTAMP,  # record last-modification time
    t_create    TIMESTAMP,  # record creation time
    val INT
);

Create the table, then insert into it as follows a record for which both TIMESTAMP columns are set to NULL, to initialize them to the current date and time:

mysql> INSERT INTO tsdemo2 (t_update,t_create,val) VALUES(NULL,NULL,5);
mysql> SELECT * FROM tsdemo2; +----------------+----------------+------+ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Reference Manual

MySQL Reference Manual

Michael Widenius, David Axmark, Kaj Arno
High Performance MySQL

High Performance MySQL

Jeremy D. Zawodny, Derek J. Balling
MySQL Stored Procedure Programming

MySQL Stored Procedure Programming

Guy Harrison, Steven Feuerstein

Publisher Resources

ISBN: 0596001452Catalog PageErrata