Another solution is to build generated columns from your DATETIME
/DATE
source.
ALTER TABLE stats
ADD COLUMN year SMALLINT GENERATED ALWAYS AS (YEAR(stat_date)) NOT NULL,
ADD COLUMN month smallint GENERATED ALWAYS AS (MONTH(stat_date)) NOT NULL;
Background
I had a similar problem. After reading this thread, I decided to store incomplete dates (with zeros). It worked on older versions of MySQL, but newer versions produced "Incorrect date" error. As mentioned before, you can turn the error into warning using the NO_ZERO_IN_DATE
setting. But the setting itself is deprecated. Hence, in the future, it would only be possible to support zeros in dates by disabling the strict mode, thus, silencing other types of errors.
Because NO_ZERO_IN_DATE is deprecated, it will be removed in a future MySQL release as a separate mode name and its effect included in the effects of strict SQL mode.
My requirement was to build a monthly view of a table. I had to add an index on month. So, computing moth on-the-fly with YEAR()
and MONTH()
was not an option.
Generated columns served their purpose. The year
and month
columns weren't part of the primary index, and I could even save space thanks to the VIRTUAL
(not STORED
) generated columns.
Links
- https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_in_date
- https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html