Timestamp for row creation and last modification - mysql

I need to keep track of the time a row was inserted into the database, and the time it was last modified.
I tried to create two separate columns, and use CURRENT_TIMESTAMP:
create table def (
id int,
creation timestamp
default CURRENT_TIMESTAMP,
modification timestamp
on update CURRENT_TIMESTAMP
);
However, this produced an error:
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
What is the best way to do this?
I'm thinking stored procedure, but looking for a standard solution. I'm also concerned with access privileges -- as few programs/things should be able to touch the timestamps as possible.
Although I would prefer MySQL answers, solutions for other RDBMS's are also appreciated!

Ya this is a lame limitation on MySQL. If you are going through an application you can add a time() call for the created_at column, and let the updated_at column use the CURRENT_TIMESTAMP.
$sql = "INSERT INTO my_table SET name = 'Mike', created_at = " . time();
I'd opt to do this on the created_at column as it probably won't be touched as often as the updated_at column.
-- Edit --
Better yet, use MySQL's built in now() function. This way you only need to be concerned with the timezone of the mysql server, and not the timezones of the app server AND the mysql server.
$sql = "INSERT INTO my_table SET name = 'Mike', created_at = NOW()";

You can use a trigger. The application can also set the value, but if do, it will be overwritten by the database.
delimiter //
CREATE TRIGGER def_bef_update BEFORE UPDATE ON def FOR EACH ROW BEGIN
SET NEW.modification = CURRENT_TIMESTAMP;
END//
delimiter ;
You can also use it to check the data and update your modification date only if has important changes.

Related

How to insert local time with mysql trigger

Have a shared server and running a mysql trigger in which time is being inserted into a column as follows -
Insert INTO mytable SET time=now();
The table and the column time then gets a GMT time.
I want that local time is inserted into that table and column.
Tried this code but still giving GMT time on insertion -
set #localtime = CONVERT_TZ('now()','GMT','+5:30');
Insert INTO mytable SET time=#localtime;
The column time has settings of TIMESTAMP as default and if I change the settings to Varchar, it gives error - "#1048 - Column 'time' cannot be null"
Please help.
I found answer to this question -
set #localtime = (SELECT CONVERT_TZ('now()','##session.time_zone','+5:30'));
Insert INTO mytable SET time=#localtime;

MySql Timestamp Trigger Preventing New Inserts

I've attempted to create a trigger to update the CREATED_DATE field of my table when a new row is inserted, but it ends up breaking the Java Application.
Basically I have an NMS that is writing to the MySql server when there is an alarm. I created the following trigger because the Java application is not applying a timestamp to alarm creation (even though there is a field for it):
CREATE TRIGGER alarm_timestamp AFTER INSERT on Alarm_Details FOR EACH ROW UPDATE Alarm_Details SET CREATED_DATE = NOW() WHERE ID = NEW.ID;
After I make this trigger, the alarms never write to the table. Then I drop the trigger and they instantly work again.
Is there a problem with the way I wrote the trigger? I'm surprised a trigger in the Sql server is preventing the application from submitting an insert query.
I have now tried to add a default value to the column with the following:
alter table Alarm_Details add constraint df_alarm_time default NOW() for CREATED_DATE;
I get a syntax error though near 'default NOW() for CREATED_DATE.'
I also tried:
ALTER TABLE Alarm_Details ALTER CREATED_DATE SET DEFAULT NOW();
It doesn't like NOW, CURRENT_TIMESTAMP, or anything. The column is set to type datetime.
I am using MySql 5.5.25.

How to submit a timestamp to a MySQL database

I have a MySQL table which hen created automatically puts a ISO 8601 timestamp into one of the fields. It does this because I have set the default value thought phpMyAdmin to TIMESTAMP.
When I update the field I want to add another timestamp to another field. Obviously I cant do that using the default option. Is there an SQL command to add a current timestamp to a field? I have had a quick read through the MySQL website but I couldnt find a way to do it...
I also had a look to see if there was a way of generating an ISO8601 timestamp through PHP but I couldnt figure out a way to convert from a PHP/unix timestamp to ISO8601.
Cheers!
MySQL can automatically initialise and/or update a single TIMESTAMP type column within every table to the current time on INSERT and UPDATE. As explained in Automatic Initialization and Updating for TIMESTAMP:
One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.
In your case, because you want separate columns to hold the record's initialisation and update times, you will need to set one (or both) of those columns explicitly; one can explicitly set a date/time column to the current date/time in SQL using the NOW() function:
INSERT INTO my_table (created) VALUES (NOW());
UPDATE my_table SET updated = NOW();
One can even use triggers to achieve the automatic behaviour that is not natively provided by MySQL:
CREATE TRIGGER set_init_time AFTER INSERT ON my_table FOR EACH ROW
SET NEW.created = NOW();
CREATE TRIGGER set_updt_time AFTER UPDATE ON my_table FOR EACH ROW
SET NEW.updated = NOW();

What is the best way to set up last-modified and date-record-added fields?

Hi I would like to set and forget two fields for tracking the date the record was added and also the date the record was last modified in a mySQL database.
I am using "ON UPDATE CURRENT_TIMESTAMP" and was hoping I would just change UPDATE to INSERT.
No luck however. Can anyone give me the heads up on the best way to achieve this? - preferably inside the database itself.
This assumes MySQL 5. Simply add two triggers:
create table foo (a1 INT, created timestamp, updated timestamp) engine=innodb;
DELIMITER |
CREATE TRIGGER foo_created BEFORE INSERT ON foo
FOR EACH ROW BEGIN
SET new.created := now();
SET new.updated := now();
END;
|
CREATE TRIGGER foo_updated BEFORE UPDATE ON foo
FOR EACH ROW BEGIN
SET new.updated := now();
END;
|
DELIMITER ;
insert into foo (a1) values(7);
select * from foo;
update foo set a1=9;
You basically need both columns to be setup as timestamps with default values of CURRENT_TIMESTAMP. Unfortunately, this is not allowed in MySQL:
Error Code: 1293
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
You can't have two timestamp columns, even though you need one to only have a default value of CURRENT_TIMESTAMP, and the other one to be UPDATE CURRENT_TIMESTAMP, this is still not allowed.
Your best bet here would be to specify as so:
CREATE TABLE `test` (
`addedDate` dateTime,
`lastModified` timestamp on update CURRENT_TIMESTAMP
)
Unfortunately, you'll have to set the 'addedDate' manually on insert using the NOW() function.
mySQL has a NOW() function you can use, see the tutorial at Tutorials Point that can help you put it in place.
You could add a DATETIME column and set it when you create the row of data. That will serve as the date the record was added.
Next, add a TIMESTAMP column:
Automatic updating of the first TIMESTAMP column in a table occurs under any of the following conditions:
You explicitly set the column to NULL.
The column is not specified explicitly in an INSERT or LOAD DATA INFILE statement.
The column is not specified explicitly in an UPDATE statement and some other column changes value. An UPDATE that sets a column to the value it does not cause the TIMESTAMP column to be updated; if you set a column to its current value, MySQL ignores the update for efficiency.
The TIMESTAMP column will take care of your record modified date.

Set field to automatically insert time-stamp on UPDATE?

I have a table with a DEC field named product_price and I wanted to add a field called price_updated_date. Is there a way to set the table to automatically insert the current time-stamp whenever the product_price field has been updated?
If not, is there a way to set it to insert the current time-stamp any time the entry is updated at all?
update:
It seems like using a trigger is the best option here. I am new to triggers and having some trouble creating it. Here is my code:
CREATE TRIGGER price_update
AFTER UPDATE ON cart_product
FOR EACH ROW
IF(OLD.product_price != NEW.product_price)
THEN
UPDATE cart_product
SET price_updated_date = CURDATE()
WHERE product_id = NEW.product_id
This is giving me this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
Why not set properties for that field as:
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
yup, create trigger after update on your table
CREATE TRIGGER price_update AFTER UPDATE on _table_ FOR EACH ROW UPDATE _table_ SET price_updated_date = CURTIME() where id=NEW.id
I note you're using MySQL
The default behaviour of a MySQL timestamp field is to default to NOW() on insert AND on update
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
I know this isn't dependant on which column has been updated as you require, but may be of some use to you or someone else browsing this question.
Its a 5-second job - just add a timestamp field & hey presto
Anytime you run an update statement, make sure you do something like this:
UPDATE table SET `product_price` = 'whatever', price_updated_date = NOW()
This will always insert the current date/time when you change the row.
Use a database trigger:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html