MySQL: Unable To Create Generated Column With Expression That Uses DATE_ADD() Function

Posted on

Question :

There might be a really obvious solution to my question, but I am stuck and did not manage find out what I am doing wrong, so you guys might tell me.

I am not able to create a nullable stored column for my expression using the DATE_ADD function in MySQL 8.

See the following example:

ADD COLUMN `test` TIMESTAMP GENERATED ALWAYS AS (DATE_ADD(col1, INTERVAL col2 HOUR)) STORED NULL;

col1 is TIMESTAMP and col2 is INT

MySQL does not complain, but just converts the expression to

(`col1` + interval `col2` hour)

And the resulting is not nullable as well.

Answer :

Mysql has done, what you ask of him.
here are more infomration

DATE_ADD(col1, INTERVAL col2 HOUR) is equal to (col1 + interval col2 hour)

And is set as Default Value for the column. so when you add a NULL you get what ever (col1 + interval col2 hour) represents.

So you can’t achieve a Nullable and generated Column at the same time.

If You need A NULL there, you have to generate the test column VALUE at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *