Automatically insert timestamp if there isn't any in the table - mysql

I have a table where I have a long list of timestamps and there could be chances of timestamps missing for an entire day or days and I want to insert a single timestamp for that particular day
For example if there is no timestamp for 2014-04-04 I want it to insert 2014-04-04 00:00:00 for that particular day.
Can this be done in mysql ?

Yes it can.
Add a trigger for after insert to the table. Make the trigger insert the current timestamp if none has been provided.
Or change the column to have a default value of CURRENT_TIMESTAMP.
Those don't resolve the problem of previous entries having no values, but it does fix the problem for the future. Filling in the rest should be a straightforward update: update mytable set its_timestamp = date(datefield) where its_timestamp is NULL.

Related

MYSQL query disallowing a timestamp column having two values from the same date

For example if a user inserts '2017-03-13 12:16:18.0' into the timestamp column,
the same user should not be allowed to enter another value in this column IF IT'S ON THE SAME DAY i.e 2017-03-13 (in this case). Or ultimately, update the timestamp column with the previously inserted value ('2017-03-13 12:16:18.0') each time the user tries to insert a timestamp date twice ON THE SAME DAY. I hope I've been explicit enough.
Below is a non-functioning query I came up with, but it shows what I would like the query to do ultimately. Thanks for your help and feedbacks.
INSERT INTO hr.entry(id,entry_time)
VALUES (45,
CASE WHEN '13-03-2017'= CAST(SYSDATE() AS date) THEN
(UPDATE hr.entry
SET entry_time =
(SELECT entry_time
FROM hr.entry
WHERE id=45
AND CAST(entry_time AS date)= CAST(SYSDATE() AS date) )
ELSE
SYSDATE());
You could add a DATE column to your table, and add a unique index to that column. Then, when you insert the timestamp into the timestamp column, you could also insert the date from that timestamp into the DATE column. Attempts to insert a timestamp whose date component already exists in that table would cause MySQL to throw an error.
I think you are going to need a trigger, unless you store the timestamp as a string using YYYY-MM-DD HH:MI:SS format. I don't really recommend that.
So, create a trigger that updates a column called timestamp_date. This simply extracts the date part of the timestamp.
With this column, you can define a unique index:
create unique index entry_userid_timestampdate on entry(userid, timestamp_date);
This will then enforce your condition.
If you decide that you want to store the timestamp as a string, you don't need the trigger (although will need to manually set the "timestamp"). Instead, you can use a prefix:
create unique index entry_userid_timestampstr on entry(userid, left(timestamp_date, 10));

Is it possible to set up multiple automatic TIMESTAMP columns in MySQL for to track changes made in every column?

MySQL Database will be being modified using a PHP Crud system, and I need to track when each record was modified.
For example, if my table has 30 rows, and 30 columns, and I want to put a "Last Modified" beside each individual entry, can I somehow set up 30 TIMESTAMP columns related to each existing column to achieve that?
Or is there a better way?
Here's what I basically want:
Column 1 C1s TIMESTAMP Column 2 C2s TIMESTAMP Column 3 C3s TIMESTAMP...
Red (lastModified) Green (lastModified) Blue (lastModified)
Orange (lastModified) Purple (lastModified) Pink (lastModified)
Yellow (lastModified) Black (lastModified) Brown (lastModified)
... etc
It should be possible to determine which column changed though. As you have access to the OLD and NEW values, you could check for every field if it changed and if it changed enter a new timestamp into the according field. Something like:
CREATE TRIGGER updateTable
BEFORE UPDATE ON tableA
FOR EACH ROW
BEGIN
IF OLD.field1 != NEW.field1 THEN
SET NEW.timestamp1 = now()
END IF;
IF OLD.field2 != NEW.field2 THEN
SET NEW.timestamp2 = now()
END IF;
END
I think that might work, but I haven't tested it.
Not with the native MySQL auto initializing TIMESTAMP/ DATETIME functionality alone.
As of Mysql 5.6.5 you can have as many auto intitializing TIMESTAMP (or DATETIME) columns as you want, however these work at the level of the record, not column.
What I mean by this is you can auto set any TIMESTAMP on creation to the CURRENT_TIMESTAMP. You can also set the TIMESTAMP column to update on modification of the RECORD. However, all columns set to update timestamps on modifcation will update when any column is updated (http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html)
Given this, it only makes sense to have at most 2 auto TIMESTAMP columns: one for recording the creation date, the other for the modification date.
Here's how you create auto incrementing timestamp columns:
ALTER TABLE sometable
ADD COLUMN created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN modified_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
There is no way with just the auto timestamp functionality to only update when a specific column is modified.
You'd need to implement a trigger with a custom procedure to accomplish your need.
Another way to do what you want as a subset of a greater facility would be to implement a change log. Place a trigger on every table. In each trigger, write an "audit entry" record into a table which has details determined by the trigger logic: which field changed, the old value, the new value, and the timestamp when it occurred.
The audit entry could have an autofilled timestamp instead of explicitly managing it. With a little bit of cleverness, the triggers could feed a common stored procedure which accepts a tablename parameter as well as the other information.
This would provide a complete history of all changes, not just the last one.

MySQL date column auto fill with current date

I have a table where I have a date column. Is there a way for MySQL to auto fill this field whenever I insert a new registry with the current date? Or is this made automatically by default?
P.S.: I'm using PHPMyAdmin
Although it is an old post, maybe this image will help as it is more explicit:
(For phpMyAdmin users)
This configuration sets that field with a value like:
2015-12-11 07:50:47
PS: Note that the timestamp will set the time OF your server!! (i.e. the example above got the time from Pacific Time (07:50:47) but it could have been from a Spanish user at 16:50:47 local time) Keep this in mind.
Also, if you already have a "Created Date" you might need another column that updates the modification date whenever there is an update:
You only need to set on update CURRENT TIME STAMP in Attributes Field.
Ready to rock!
Set Default to in your mySql query
CURRENT_TIMESTAMP
you have to use
now()
function where you want to fill current time.
i.e.:
INSERT INTO user_rights (`user_id`,`right`,`group_id`,`created_date`) VALUES ( '42', '160', '1', now());
I realize this may not be a direct answer to the question but I do believe this is the most useable solution.
I highly recommend using a DATETIME or TIMESTAMP data type for the column in question.If you are utilizing a fairly current version of MySQL, MySQL will do the work for you.
Details:
To be very clear, as of 5.6.5, for both the TIMESTAMP & DATETIME datatypes, you can do the following:
Set a DEFAULT value of the current date & time (using NOW() or one of its aliases such as CURRENT_TIMESTAMP)This means every time you insert a new row into this table a TIMESTAMP or DATETIME column with this default will get the current date and time
Set an ON UPDATE constraint that will UPDATE a column to the current date & time when, (you guessed it) the row is updated
Here's how:
An Example in a CREATE TABLE statement:
CREATE TABLE t1 (
ts1 DATETIME ON UPDATE CURRENT_TIMESTAMP
,ts2 DATETIME DEFAULT NOW()
);
Please note that DATETIME can be replaced with TIMESTAMP for effectively the same functionality.
Additionally I suggest the use of the DATETIME data type over TIMESTAMP as DATETIME has a much larger range of dates it can support. It's worth mentioning that TIMESTAMP is smaller for those few cases that matters. For more details please read my answer here: https://stackoverflow.com/a/26117532/1748266
I have added this to my table and it works
ALTER TABLE Medewerkers ADD med_created TIMESTAMP DEFAULT now();
When you insert data into your record it update automatically the med_created
MySQL unfortunately doesn't allow specifying values other than constants as the default for columns other than TIMESTAMPs.
This is a feature available in MySQL versions 8.0+, but for older versions the only solution for a database defined default would be to use a trigger.
You can do something like this from the SQL screen
ALTER TABLE `table_name` CHANGE `created_at` `created_at` TIMESTAMP NOT NULL

MySQL: Trying to insert a value in a timestamp throws an error

I have a table with this column:
last_modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
And it looks like I can not insert a row with a custom timestamp, I get this error:
Incorrect datetime value: '1145868501' for column 'last_modified' at row 1
I am trying to populate this table with data coming from another table, that other table only has a creation_time field which is a DATETIME so I use UNIX_TIMESTAMP(creation_time) to populate the timestamp.
I think the timestamp column with "DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" prevents me from inserting my own stuff, am I right? If yes where is the official doc about that, and what is the best solution? Creating a simple timestamp first then alter the table after inserting data?
Thanks!
EDIT: since people are advising me to not use UNIX_TIMESTAMP, I have to say that I didn't want to use that at the beginning, but I got this kind of error:
Incorrect datetime value: '2010-03-28 02:15:51' for column 'last_modified'
So I thought I had to insert a "real" timestamp...
You can explicitedly insert a value in a TIMESTAMP column. Read: TIMESTAMP Properties
The auto-update TIMESTAMP column, if there is one, is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. If all other columns are set to their current values, the TIMESTAMP column does not change. Automatic updating does not apply if the TIMESTAMP column is explicitly assigned a value other than NULL.
Update
Hehe, the error occurs because - well- there was no datetime with '2010-03-28 02:15:51'! This was in the daylight saving time gap (which usually appears some day in March, between 02:00 - 03:00 or 03:00 - 04:00.
See: Daylight Saving Time explanation.
You're trying to put a long integer into a datetime field. That doesn't work. Remove the call to UNIX_TIMESTAMP() and it should work.
The MySQL TIMESTAMP type is almost identical to a DATETIME; it just has some extra auto-update magic. As far as SELECT and UPDATE is concerned, it is a DATETIME.
If the column is always auto-updated, you can remove the property, getters and setters from the Entity.
Doing this way, it will be ignored in all queries.

I need to select a timestamp and insert a date

I have a timestamp in a database table. Now everytime a record is amended the timestamp changes - this isn't really what I want as the record represents a sale so everytime the data is amended it looks like the sale time has changed! Thus I have added a new field to the database table called 'sale_date' and I want to select the timestamp field of that record, called 'sale_time' and convert the timestamp to the format dd/mm/yyyy hh:mm:ss. and insert it into the new 'sale_date' field (which is text not date)
Any ideas? I'm rubbish at mysql.
If I haven't explained myself well please say.
The definition of your timestamp column (one that changes on updates) constains ON UPDATE CURRENT_TIMESTAMP clause. Remove it (ALTER TABLE) and it will stop updating.
And please, pleasee, please, do not ever store dates as text.