Choosing a Temporal Data Type
Problem
You need to store temporal data but aren’t sure which is the most appropriate data type.
Solution
Choose the data type according to the characteristics of the information to be stored and how you need to use it. Consider questions such as these:
Do you need times only, dates only, or combined date and time values?
What range of values do you require?
Do you want automatic initialization of the column to the current date and time?
Discussion
MySQL provides
DATE
and TIME
data types for representing date and
time values separately, and
DATETIME
and
TIMESTAMP
types for combined
date-and-time values. These values have the following
characteristics:
DATE
values are handled as strings inCCYY-MM-DD
format, whereCC
,YY
,MM
, andDD
represent the century, year within century, month, and day parts of the date. The supported range forDATE
values is1000-01-01
to9999-12-31
.TIME
values are represented as strings inhh:mm:ss
format, wherehh
,mm
, andss
are the hours, minutes, and seconds parts of the time.TIME
values often can be thought of as time-of-day values, but MySQL actually treats them as elapsed time. Thus, they may be greater than23:59:59
or even negative. (The actual range of aTIME
column is-838:59:59
to838:59:59
.)DATETIME
andTIMESTAMP
values are represented as combined date-and-time strings inCCYY-MM-DD
hh:mm:ss
format. (Before MySQL 4.1,TIMESTAMP
display format wasCCYYMMDDhhmmss
numeric format. Older applications that depend on this display ...
Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.