The TIMESTAMP
data type holds values that contain both date and time, fixed at 19 characters. The format of a TIMESTAMP
is 'YYYY-MM-DD HH:MM:SS'
In DBMSs such as MySQL, DATETIME
is a supported data type that, just like TIMESTAMP
, is used to hold date and time values, but they're not entirely the same for the following reasons:
- Size:
DATETIME
requires a few more bytes for data storing thanTIMESTAMP
. - As specified in the MySQL documentation, MySQL converts
TIMESTAMP
values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval, which does not occur for other types such asDATETIME
. This is particularly convenient when working with different time zones. - Different supported ranges: '1000-01-01 00:00:00' to '9999-12-31 23:59:59' for
DATETIME
, '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC forTIMESTAMP
.
Retrieving data from TIMESTAMP
:
In order to fetch information from a TIMESTAMP
object, we can use the extract()
function, for which we specify the field from TIMESTAMP
we want. Examples of this field would be:
Let's consider the following table to work on some examples:
All payments were made in november, so let's grab these bills along with the days they were paid:
We add the AS statement to name the resulting column from using EXTRACT.
If our bills table was larger, including payments to these bills all throughout the year, we could implement extract() and an aggregate function (SUM) to show, for example, the total amount of money paid in bills by month, with a query similar to this one:
The larger our databases, the more ways available to retrieve info!
Have fun!
Top comments (4)
Super nice explanation. Thanks for sharing Wendy.
Glad you liked it! 😊
Thank you. This makes more sense than any documentation I've read elsewhere. :)
Sorry for the laaaate reply! Glad you found it useful!