how to insert date in mysql table - mysql

I have a mysql table called pollOfTheWeek. It has a column "pollDate" of type date. I have two questions regarding this :
1. I declared the column while creating the table as [pollDate date] What I wanted is that this column be set automatically, when the user doesnt enter any value for this column. How do i declare the column to achieve this?
Assuming that I have the same declaration as above, how do I enter an empty value. I mean if the column was of type varchar, I would enter empty value as " ". But since it is of type date, I get error when I enter the value as " ". How do I enter empty value for the pollDate column?

You need to create a trigger:
CREATE TRIGGER triggerName
BEFORE INSERT ON yourTable
FOR EACH ROW
SET NEW.date = coalesce(NEW.date, curdate());
The empty value would be null.

MySQL has an extremely limited support for default values. In general, it must be a constant expression like '0' or '(none)' and functions are not allowed. The only exception I'm aware of is that you can set CURRENT_TIMESTAMP as default value for a TIMESTAMP column; however, this is not available for DATE or DATETIME columns. Unluckily, TIMESTAMP has a smaller range and contains time information.
So your options are:
Do it in your client application by setting NOW() as value in your inserts.
Write a trigger:
.
CREATE TRIGGER pollOfTheWeek_trg BEFORE INSERT ON pollOfTheWeek
FOR EACH ROW SET NEW.pollDate = NOW();
As about empty values, I would simply use NULL. Why use empty strings?

there is no way to automatically set a DATE column to the current date/time in mysql. TIMESTAMPs can be automatically set to the current time though. alternatively, just pass NOW() as a parameter when you insert :
INSERT INTO pollOfTheWeek (name, pollDate) VALUES ('someName', NOW());
as to your other question, you probably want to allow NULL values in the date column and set them to NULL when there is no date given.

Related

How do I insert current date as a column in a mysql table that will automatically update [duplicate]

If I have a column in a table of type TIMESTAMP and has as default: CURRENT_TIMESTAMP does this column get updated to the current timestamp if I update the value
of any other column in the the same row?
It seems that it does not but I am not sure if this is what should happen.
I can not understand what this means (from MySQL documentation):
If the column is auto-updated, it is automatically updated to the
current timestamp when the value of any other column in the row is
changed from its current value. The column remains unchanged if all
other columns are set to their current values. To prevent the column
from updating when other columns change, explicitly set it to its
current value. To update the column even when other columns do not
change, explicitly set it to the value it should have]2
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP means that any INSERT without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP and DATETIME columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMPs) When you use TIMESTAMPs, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
I think you have to define the timestamp column like this
CREATE TABLE t1
(
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
See here
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.
To explain it let's imagine you have only one row:
-------------------------------
| price | updated_at |
-------------------------------
| 2 | 2018-02-26 16:16:17 |
-------------------------------
Now, if you run the following update column:
update my_table
set price = 2
it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).
But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.
Add a trigger in database:
DELIMITER //
CREATE TRIGGER update_user_password
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
IF OLD.password <> NEW.password THEN
SET NEW.password_changed_on = NOW();
END IF;
END //
DELIMITER ;
The password changed time will update only when password column is changed.
Adding where to find UPDATE CURRENT_TIMESTAMP because for new people this is a confusion.
Most people will use phpmyadmin or something like it.
Default value you select CURRENT_TIMESTAMP
Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP

MySQL: How to set a DATE column by converting all values in a VARCHAR column?

I have a table in which there is a column called "DATE" which contains dates in the format "23-Nov-2017" as datatype VARCHAR. I'm trying to convert this VARCHAR column and store it in a new column called "NEWDATE" of datatype DATE.
I have created the new column "NEWDATE" of type DATE and I am trying to use the STR_TO_DATE() function to perform the conversion. However, I can't get it to work for some reason.
UPDATE table SET NEWDATE = STR_TO_DATE(DATE,'%d-%m-%Y');
The NEWDATE column is not updated with any values after the statement. I guess this means that the statement does not execute. What am I doing wrong?
EDIT: I have also tried STR_TO_DATE(DATE,'%d-%b-%Y'). However there is still no change to the values in the NEWDATE column
Your format '%d-%m-%Y' does not match your actual date string "23-Nov-2017"
The %m is for numeric month and you have an abbreviated text month
Use %b for 3 char month values like this:
STR_TO_DATE(DATE,'%d-%b-%Y')
EDIT: WorkBench issue
That is just a Workbench config setting to stop you accidentally issuing a HUGE update. You can either turn that setting OFF or frig it a bit by giving it a WHERE clause that will allow it to run like below. Below assumes this table has an id column
UPDATE table SET NEWDATE = STR_TO_DATE(DATE,'%d-%b-%Y') WHERE id<10000000;
Or
UPDATE table SET NEWDATE = STR_TO_DATE(DATE,'%d-%b-%Y') WHERE id>0;

How to make a column update timestamp automatically based on update on selected columns only? [duplicate]

If I have a column in a table of type TIMESTAMP and has as default: CURRENT_TIMESTAMP does this column get updated to the current timestamp if I update the value
of any other column in the the same row?
It seems that it does not but I am not sure if this is what should happen.
I can not understand what this means (from MySQL documentation):
If the column is auto-updated, it is automatically updated to the
current timestamp when the value of any other column in the row is
changed from its current value. The column remains unchanged if all
other columns are set to their current values. To prevent the column
from updating when other columns change, explicitly set it to its
current value. To update the column even when other columns do not
change, explicitly set it to the value it should have]2
Give the command SHOW CREATE TABLE whatever
Then look at the table definition.
It probably has a line like this
logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
in it. DEFAULT CURRENT_TIMESTAMP means that any INSERT without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP means that any update without an explicit timestamp results in an update to the current timestamp value.
You can control this default behavior when creating your table.
Or, if the timestamp column wasn't created correctly in the first place, you can change it.
ALTER TABLE whatevertable
CHANGE whatevercolumn
whatevercolumn TIMESTAMP NOT NULL
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable without changing the timestamp, that is,
To prevent the column from updating when other columns change
then you need to issue this kind of update.
UPDATE whatevertable
SET something = 'newvalue',
whatevercolumn = whatevercolumn
WHERE someindex = 'indexvalue'
This works with TIMESTAMP and DATETIME columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMPs) When you use TIMESTAMPs, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.
I think you have to define the timestamp column like this
CREATE TABLE t1
(
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
See here
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.
To explain it let's imagine you have only one row:
-------------------------------
| price | updated_at |
-------------------------------
| 2 | 2018-02-26 16:16:17 |
-------------------------------
Now, if you run the following update column:
update my_table
set price = 2
it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).
But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.
Add a trigger in database:
DELIMITER //
CREATE TRIGGER update_user_password
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
IF OLD.password <> NEW.password THEN
SET NEW.password_changed_on = NOW();
END IF;
END //
DELIMITER ;
The password changed time will update only when password column is changed.
Adding where to find UPDATE CURRENT_TIMESTAMP because for new people this is a confusion.
Most people will use phpmyadmin or something like it.
Default value you select CURRENT_TIMESTAMP
Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP

Data truncated for column startDate1 at row

I have 2 columns startdate and enddate of type int. These columns are used to store timestamp data.
Now I have to extract the date component from this timestamp, convert it back to timestamp an store it in another column startdate1 of type int
But on doing this, I get a warning 'Data truncated for column startDate1 at row'.
The sql queries are:-
ALTER TABLE `ServiceRule` ADD COLUMN `startDate1` INT(11) NULL DEFAULT NULL AFTER `endDate` , ADD COLUMN `endDate1` INT(11) NULL DEFAULT NULL AFTER `startDate1`;
update `ServiceRule` set `startDate1`= TIMESTAMP(DATE(from_unixtime(`startDate`)));
update `ServiceRule` set `endDate1`= TIMESTAMP(DATE(from_unixtime(`endDate`)));
Now if i change the datatype of startDate1 and endDate1 to TIMESTAMP, the first update query of startDate1 runs successfully.
But the endDate1 update query shows the warning 'Out of range value for column 'endDate1' at row'.
After browsing for solution, i got know that this occurs if the input value is greater than the column datatype range.
Can anybody please try to help me out?
Thanks in Advance. :)
I think what you want is UNIX_TIMESTAMP instead of TIMESTAMP.
UNIX_TIMESTAMP is the inverse function of FROM_UNIXTIME.
What means that one of the rows contains a value that cannot be converted to int because indeed it is either too more or too less than expected.
Can't you just convert the columns to timestamp and do the extraction from there? Try to query per set of 100 for example and narrow down the faulting row.
When the field startDate is of type int, then alter table statement used is not correct to achieve what you wanted.
Change it as below:
-- keeping the added fields as is, execute the following
ALTER TABLE `ServiceRule` MODIFY COLUMN `startDate1` DATETIME DEFAULT NULL;
ALTER TABLE `ServiceRule` MODIFY COLUMN `endDate1` DATETIME DEFAULT NULL;
update `ServiceRule` set `startDate1`= TIMESTAMP(DATE(from_unixtime(`startDate`)));
update `ServiceRule` set `endDate1`= TIMESTAMP(DATE(from_unixtime(`endDate`)));

MySQL (DEFAULT + ON UPDATE) TIMESTAMPs

I've a table where I've two fields:
dateCreated
dateUpdated
I want both fields to hold timestamps, dateCreated to have a DEFAULT CURRENT TIMESTAMP flag and dateUpdated to have a ON UPDATE CURRENT TIMESTAMP behavior, however seems that I can't have more than one timestamps field types on the same table.
It would be really useful if the database could take care of this for me, can I circumvent this issue somehow?
YES WE CAN.
You can use a trigger to update the field, like so:
create trigger CreationTimestamp after insert on MyTable for each row
begin
update MyTable set CreateField = UpdateField where id = new.id
end
This way, you can set your auto-update field using the native MySQL method, and use this to capture the creation date.