I must save dates and times in different tables of a typical transactional application where I am going to store various information, such as:
- Dates and times at which each transaction occurs (Invoice, Payment Receipt, etc.)
- Dates and times of future events, such as appointments and scheduled deliveries
- Past dates, such as the date of birth of the employee, or of the employee's children.
I have little experience with MySQL and I'm not sure which data type I should choose in each case.
What is recommended, use a field of type DateTime or type TimeStamp and why?
At some point in this MySQL documentation it states something like this: http://dev.mysql.com/doc/refman/5.7/en/datetime.html (English link)
Starting from the above and taking it into account, it is possible that the range of data that you could store or be interested in might tilt you in favor of one or the other, for example, if you work with mortgages, to say the least, it is easy for you to exceed the range
TIMESTAMP
today.TIMESTAMP
is affected by time zone settings/adjustments. As long as itDATETIME
is constant.TIMESTAMP
is four bytes andDATETIME
eight bytes, therefore timestamps (TIMESTAMP
) are also lighter in the database, with faster indexing.With all of the above in mind if you want to store a specific value "it might be better" to use
DATATIME
, but if you just want to store to keep track of possible record changes you might want to useTIMESTAMP
when a record changes.If you are working on
MySQL 5
or above, the values ofTIMESTAMP
are converted from the current time zone to UTC for thealmacenamiento
, and are converted back from UTC to the current time zone for therecuperación
. only for the TIMESTAMP data type.(NOTE if I find the link of the above I will try to put it here)
I hope it helps you.
It depends on your requirements, there are certain considerations for each case, for example the range of values that each one can support.
more information: DATE, DATETIME, and TIMESTAMP types.
other properties perhaps obvious to many of us is automatic initialization and updating to the current date and time. TIMESTAMP values with a default of zero are not allowed in MySQL.
I only see the point of using
TimeStamp
it when you want to make sure that date is set automatically when the record is inserted or updated.For example, if you want to save the date and time of an event, you define it like this:
Note that in the INSERT you do not include the field
FechaHora
.Another example with UPDATE: