I want to accomplish the following:
I field in a table in MySQL that, when provided with a NULL value, should resolve to the current time.
I did the following:
CREATE TABLE foo (
bar TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
baz INT
);
-- Now let's insert something.
INSERT INTO foo (bar, baz) VALUES (null, 2);
-- Now let's make sure it works as desired.
SELECT * FROM foo;
but unfortunately it doesn't work as expected:
**********
bar | baz
**********
null | 2
It only works when I leave off the column's value in an INSERT statement.
How can I make the above INSERT statement work? That is, the field should be set to the default time when the value is null.
DEFAULTconstraint is only used when the column is omited from anINSERT(or useDEFAULTfor the value) - so in order to replace or override values in anINSERTorUPDATEyou'll need to use aTRIGGER(which is non-declarative and introduces problems of its own). Instead, why not makebaraNOT NULLcolumn and ensure allINSERTstatements omit that column? Or use theDEFAULTkeyword (if MySQL supports it, I'm unsure) as:INSERT INTO foo ( bar, baz ) VALUES ( DEFAULT, 123 )