Introduction to Date and Time Functions
Explore key MySQL date and time data types and functions to efficiently create, access, modify, and compare temporal values. Understand how to use functions like CAST(), CURDATE(), DAYOFWEEK(), ADDDATE(), and DATEDIFF() for practical SQL applications involving dates and times.
We'll cover the following...
MySQL supports five categories of data types: numeric, date and time, string, spatial, and JSON. For date and time, the database management system provides a variety of data types, i.e., DATE, TIME, DATETIME, TIMESTAMP, and YEAR. The data type representing dates is DATE with values representing 'YYYY-MM-DD'. TIME represents time as 'hhh:mm:ss' where hhh denotes hours, mm represents minutes, and ss stands for seconds. The data type representing a date associated with a time of the day in MySQL is DATETIME. It is not exactly a combination of DATE and TIME but close. The format used to represent DATETIME is 'YYYY-MM-DD hh:mm:ss'. Similar to DATETIME, TIMESTAMP is the data type representing a date associated with a time of the day. However, TIMESTAMP has a more constrained range and stores time with time zone information. Finally, MySQL provides the data type YEAR with the display format YYYY to represent a single year.
We already encountered the SQL function CAST() to cast a value of any type to a value of a specified target data type. With this, CAST() can also modify temporal values. For example, we can convert a DATE to other temporal data types as follows:
To convert the data type DATE to other temporal data types, we leverage a temporary table:
First, we create a temporary table named
date_and_timewith columns for different temporal data types (DATE,TIME, ...