Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to use zero-date '0000-00-00 00:00:00' or NULL in MySQL?

Tags:

mysql

Is it a better practice to use default date '0000-00-00 00:00:00' or NULL on a MySQL database?

I have read best to use default date '0000-00-00 00:00:00' for the reason of calculations

i.e. >than a date less than a date.

Also on time best to store 00:00 or NULL if time is not known.

like image 674
Matthew Chambers Avatar asked Sep 18 '12 18:09

Matthew Chambers


People also ask

Which format is correct for giving a date in MySQL?

MySQL retrieves and displays DATE values in ' YYYY-MM-DD ' format. The supported range is '1000-01-01' to '9999-12-31' .

Is NULL and 0 the same in MySQL?

In MySQL, 0 or NULL means false and anything else means true. The default truth value from a boolean operation is 1 .

Which of the following data type stores the value in format 0000 00 00?

MySQL permits you to store a “zero” value of '0000-00-00' as a “dummy date.” In some cases, this is more convenient than using NULL values, and uses less data and index space.

Can date be NULL in MySQL?

MySQL DOES accept null values for the datetime definition, but if you for some reason think otherwise and won't use a null value, consider simply using '1000-01-01' as the value and excluding rows which have that value for your bill_date column in your queries. Mysql does allow nulls in datetime fields.


2 Answers

MySQL 5.7 defaults to disallowing 0000-00-00 00:00:00 as default value, unless you set sql_mode = ''. It seems MySQL wants you to use NULL as default value.

like image 20
bart Avatar answered Sep 18 '22 11:09

bart


You should use NULL because 0000-00-00 00:00:00 is not a valid date. If you use libraries such as moment.js or Carbon to manage date, they both know how to deal with NULL dates.

The MySQL configuration should always be set to:

SET sql_mode = 'NO_ZERO_DATE';

unless you have to deal with an old database.

That said, according to MySQL Documentation:

MySQL permits you to store a “zero” value of '0000-00-00' as a “dummy date.” This is in some cases more convenient than using NULL values, and uses less data and index space. To disallow '0000-00-00', enable the NO_ZERO_DATE mode.

If you are on Windows:

“Zero” date or time values used through Connector/ODBC are converted automatically to NULL because ODBC cannot handle such values.

An additional point to consider is: what is the true meaning of a zero date?

  • Does '0000-00-00' < '2018-12-12'?
  • Does '0000-00-00' means 'unknown'?
  • Does '0000-00-00' means 'null'?

Unless your answer is the first one and you need to do comparisons with null dates, using a NULL value is always less confusing.

like image 101
nowox Avatar answered Sep 18 '22 11:09

nowox