I have a MySql table with a field defined as:
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
On my local machine, I can run:
INSERT INTO mytbl (id, user_id, created) VALUES(88882341234, 765, null);
SELECT id, user_id, created FROM mytbl WHERE id = '88882341234';
And then 'created' will show something like '2014-06-13 21:16:42'.
But on my staging server, if I run the same queries, I get this error:
Column 'created' cannot be null.
The schemas of the tables are the same (across local and staging), which I ensured via mysqldump (to clone the table before running this test).
I'm running MySql 5.6.17 on both machines. I've also ensured that both have the same sql_mode.
What could be the problem?
P.S. For people who don't know why I'd be setting a non-nullable field's value to null, MySql Docs say:
In addition, you can initialize or update any TIMESTAMP column to the current date and time by assigning it a NULL value, unless it has been defined with the NULL attribute to permit NULL values.
To permit a TIMESTAMP column to contain NULL , explicitly declare it with the NULL attribute. In this case, the default value also becomes NULL unless overridden with a DEFAULT clause that specifies a different default value. DEFAULT NULL can be used to explicitly specify NULL as the default value.
Yes, adding a column with NOT NULL and a default doesn't actually write the values to all the rows at the time of the alter, so it is no longer a size-of-data operation. When you select from the table, the columns are actually materialized from sys.
A TIMESTAMP column that permits NULL values does not take on the current timestamp at insert time except under one of the following conditions: Its default value is defined as CURRENT_TIMESTAMP and no value is specified for the column.
MySQL CURRENT_TIMESTAMP() Function The CURRENT_TIMESTAMP() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).
I found what the problem was. The MySql variable/parameter explicit_defaults_for_timestamp
was OFF on my local machine but ON on my remote machine.
I visited my AWS RDS Parameter Groups page and changed explicit_defaults_for_timestamp from 1 to 0. Then I went to my AWS RDS instances page to watch when "Parameter Group" changed from "Applying" to "pending-reboot". Then I rebooted the particular instance.
These links helped me:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With