Last Updated: 04 July, 2023
In MySQL, we can work with dates and times using various date and time functions and data types. Here are some key aspects related to dates and times in MySQL:
Here are some examples of creating tables with date and time columns:
-- Creating a table with DATE column CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, event_date DATE ); -- Creating a table with TIME column CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, event_time TIME ); -- Creating a table with DATETIME column CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, event_datetime DATETIME ); -- Creating a table with TIMESTAMP column CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, event_timestamp TIMESTAMP ); -- Creating a table with YEAR column CREATE TABLE my_table ( id INT PRIMARY KEY AUTO_INCREMENT, event_year YEAR );
When inserting data into these tables, we need to format your date and time values accordingly:
INSERT INTO my_table (event_date) VALUES ('2023-07-04'); INSERT INTO my_table (event_time) VALUES ('12:34:56'); INSERT INTO my_table (event_datetime) VALUES ('2023-07-04 12:34:56'); -- TIMESTAMP values can be inserted using the NOW() function INSERT INTO my_table (event_timestamp) VALUES (NOW()); INSERT INTO my_table (event_year) VALUES (2023);
Formatting date or time values in a query:
SELECT DATE_FORMAT(date_column, '%Y-%m-%d') AS formatted_date FROM your_table;
That's all, guys. I hope this MySQL article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com