MySql - Date and Time data types

MySQL - Date and Time Data Types

Date and Time Data Types (DATE, DATETIME, TIMESTAMP, etc.) in MySQL 

MySQL provides a variety of data types specifically designed for storing and manipulating date and time values. These data types are essential for applications involving logs, events, time series data, and scheduling. This guide explores MySQL's date and time data types in detail, including DATE, DATETIME, TIMESTAMP, TIME, and YEAR. It also discusses formatting, time zone management, arithmetic, and functions that assist in date/time manipulation.

1. Overview of MySQL Date and Time Data Types

Data Type Format Range Storage (Bytes)
DATE YYYY-MM-DD 1000-01-01 to 9999-12-31 3
DATETIME YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:00 to 9999-12-31 23:59:59 8
TIMESTAMP YYYY-MM-DD HH:MM:SS 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC 4
TIME HH:MM:SS -838:59:59 to 838:59:59 3
YEAR YYYY 1901 to 2155 1

2. DATE Data Type

The DATE type is used to store only date values in the format YYYY-MM-DD.

2.1 Example: Creating a Table with DATE

CREATE TABLE employees (
    id INT,
    name VARCHAR(100),
    hire_date DATE
);

2.2 Inserting DATE Values

INSERT INTO employees (id, name, hire_date)
VALUES (1, 'Alice', '2024-05-01');

2.3 Retrieving DATE Values

SELECT name, hire_date FROM employees;

3. DATETIME Data Type

DATETIME is used to store both date and time components in the format YYYY-MM-DD HH:MM:SS.

3.1 Creating a Table with DATETIME

CREATE TABLE appointments (
    id INT,
    title VARCHAR(255),
    appointment_time DATETIME
);

3.2 Inserting a DATETIME Value

INSERT INTO appointments (id, title, appointment_time)
VALUES (1, 'Dental Checkup', '2024-07-12 14:30:00');

3.3 Querying DATETIME

SELECT * FROM appointments
WHERE appointment_time BETWEEN '2024-07-01 00:00:00' AND '2024-07-31 23:59:59';

4. TIMESTAMP Data Type

The TIMESTAMP data type is similar to DATETIME but is stored relative to UTC and affected by the time zone setting of the server or client.

4.1 Creating a Table with TIMESTAMP

CREATE TABLE log_events (
    id INT,
    event_description VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

4.2 Automatic Updates

CREATE TABLE documents (
    id INT,
    title VARCHAR(255),
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

4.3 Inserting and Retrieving TIMESTAMP

INSERT INTO log_events (id, event_description)
VALUES (1, 'Server started');

SELECT * FROM log_events;

5. TIME Data Type

The TIME type is used to store time intervals or times of day in HH:MM:SS format.

5.1 Creating a Table with TIME

CREATE TABLE work_shifts (
    id INT,
    shift_name VARCHAR(50),
    duration TIME
);

5.2 Inserting TIME Values

INSERT INTO work_shifts (id, shift_name, duration)
VALUES (1, 'Morning Shift', '08:00:00');

6. YEAR Data Type

Stores a four-digit year value.

6.1 Creating a Table with YEAR

CREATE TABLE car_models (
    id INT,
    model_name VARCHAR(50),
    model_year YEAR
);

6.2 Inserting a YEAR Value

INSERT INTO car_models (id, model_name, model_year)
VALUES (1, 'Tesla Model S', 2025);

7. Functions for Date and Time Manipulation

7.1 CURRENT_DATE, CURRENT_TIME, NOW()

SELECT CURRENT_DATE;
SELECT CURRENT_TIME;
SELECT NOW();

7.2 DATE_ADD and DATE_SUB

SELECT DATE_ADD('2025-01-01', INTERVAL 10 DAY);
SELECT DATE_SUB('2025-01-01', INTERVAL 1 MONTH);

7.3 DATEDIFF and TIMEDIFF

SELECT DATEDIFF('2025-01-10', '2025-01-01');
SELECT TIMEDIFF('12:30:00', '08:00:00');

7.4 EXTRACT and DATE_FORMAT

SELECT EXTRACT(YEAR FROM '2025-07-12');
SELECT DATE_FORMAT(NOW(), '%W, %M %d, %Y');

7.5 STR_TO_DATE and TIME_FORMAT

SELECT STR_TO_DATE('12-07-2025', '%d-%m-%Y');
SELECT TIME_FORMAT('13:45:00', '%h:%i %p');

8. Comparing DATETIME and TIMESTAMP

8.1 Storage and Range

  • DATETIME has a wider range but uses more storage.
  • TIMESTAMP uses less storage and is suitable for tracking events based on UTC.

8.2 Time Zone Behavior

  • DATETIME is not affected by time zone settings.
  • TIMESTAMP automatically adjusts based on the session or server time zone.

9. Time Zones and MySQL

9.1 Checking and Setting Time Zones

SELECT @@global.time_zone;
SET time_zone = '+05:30';

9.2 Using UTC_TIMESTAMP

SELECT UTC_TIMESTAMP();

10. Indexing and Date Performance Tips

  • Create indexes on date columns used in WHERE or JOIN conditions.
  • Use date range filters instead of functions on date columns for better performance.

10.1 Avoid

SELECT * FROM orders WHERE YEAR(order_date) = 2025;

10.2 Prefer

SELECT * FROM orders 
WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';

11. Practical Examples

11.1 Users Registered in the Last 7 Days

SELECT * FROM users
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);

11.2 Monthly Sales Summary

SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue
FROM orders
GROUP BY month;

11.3 Events Occurring at a Specific Time

SELECT * FROM log_events
WHERE TIME(created_at) BETWEEN '09:00:00' AND '11:00:00';

MySQL offers a powerful suite of date and time data types to handle virtually any temporal data requirement. Each typeβ€”DATE, DATETIME, TIMESTAMP, TIME, and YEARβ€”has specific use cases depending on range, storage, and time zone handling. When working with dates and times, it is important to understand their behavior, especially with regard to time zones and automatic updates. Leveraging MySQL's rich set of functions for date manipulation allows for efficient querying and transformation of temporal data.

logo

MySQL

Beginner 5 Hours
MySQL - Date and Time Data Types

Date and Time Data Types (DATE, DATETIME, TIMESTAMP, etc.) in MySQL 

MySQL provides a variety of data types specifically designed for storing and manipulating date and time values. These data types are essential for applications involving logs, events, time series data, and scheduling. This guide explores MySQL's date and time data types in detail, including DATE, DATETIME, TIMESTAMP, TIME, and YEAR. It also discusses formatting, time zone management, arithmetic, and functions that assist in date/time manipulation.

1. Overview of MySQL Date and Time Data Types

Data Type Format Range Storage (Bytes)
DATE YYYY-MM-DD 1000-01-01 to 9999-12-31 3
DATETIME YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:00 to 9999-12-31 23:59:59 8
TIMESTAMP YYYY-MM-DD HH:MM:SS 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC 4
TIME HH:MM:SS -838:59:59 to 838:59:59 3
YEAR YYYY 1901 to 2155 1

2. DATE Data Type

The DATE type is used to store only date values in the format YYYY-MM-DD.

2.1 Example: Creating a Table with DATE

CREATE TABLE employees ( id INT, name VARCHAR(100), hire_date DATE );

2.2 Inserting DATE Values

INSERT INTO employees (id, name, hire_date) VALUES (1, 'Alice', '2024-05-01');

2.3 Retrieving DATE Values

SELECT name, hire_date FROM employees;

3. DATETIME Data Type

DATETIME is used to store both date and time components in the format YYYY-MM-DD HH:MM:SS.

3.1 Creating a Table with DATETIME

CREATE TABLE appointments ( id INT, title VARCHAR(255), appointment_time DATETIME );

3.2 Inserting a DATETIME Value

INSERT INTO appointments (id, title, appointment_time) VALUES (1, 'Dental Checkup', '2024-07-12 14:30:00');

3.3 Querying DATETIME

SELECT * FROM appointments WHERE appointment_time BETWEEN '2024-07-01 00:00:00' AND '2024-07-31 23:59:59';

4. TIMESTAMP Data Type

The TIMESTAMP data type is similar to DATETIME but is stored relative to UTC and affected by the time zone setting of the server or client.

4.1 Creating a Table with TIMESTAMP

CREATE TABLE log_events ( id INT, event_description VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );

4.2 Automatic Updates

CREATE TABLE documents ( id INT, title VARCHAR(255), updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );

4.3 Inserting and Retrieving TIMESTAMP

INSERT INTO log_events (id, event_description) VALUES (1, 'Server started'); SELECT * FROM log_events;

5. TIME Data Type

The TIME type is used to store time intervals or times of day in HH:MM:SS format.

5.1 Creating a Table with TIME

CREATE TABLE work_shifts ( id INT, shift_name VARCHAR(50), duration TIME );

5.2 Inserting TIME Values

INSERT INTO work_shifts (id, shift_name, duration) VALUES (1, 'Morning Shift', '08:00:00');

6. YEAR Data Type

Stores a four-digit year value.

6.1 Creating a Table with YEAR

CREATE TABLE car_models ( id INT, model_name VARCHAR(50), model_year YEAR );

6.2 Inserting a YEAR Value

INSERT INTO car_models (id, model_name, model_year) VALUES (1, 'Tesla Model S', 2025);

7. Functions for Date and Time Manipulation

7.1 CURRENT_DATE, CURRENT_TIME, NOW()

SELECT CURRENT_DATE; SELECT CURRENT_TIME; SELECT NOW();

7.2 DATE_ADD and DATE_SUB

SELECT DATE_ADD('2025-01-01', INTERVAL 10 DAY); SELECT DATE_SUB('2025-01-01', INTERVAL 1 MONTH);

7.3 DATEDIFF and TIMEDIFF

SELECT DATEDIFF('2025-01-10', '2025-01-01'); SELECT TIMEDIFF('12:30:00', '08:00:00');

7.4 EXTRACT and DATE_FORMAT

SELECT EXTRACT(YEAR FROM '2025-07-12'); SELECT DATE_FORMAT(NOW(), '%W, %M %d, %Y');

7.5 STR_TO_DATE and TIME_FORMAT

SELECT STR_TO_DATE('12-07-2025', '%d-%m-%Y'); SELECT TIME_FORMAT('13:45:00', '%h:%i %p');

8. Comparing DATETIME and TIMESTAMP

8.1 Storage and Range

  • DATETIME has a wider range but uses more storage.
  • TIMESTAMP uses less storage and is suitable for tracking events based on UTC.

8.2 Time Zone Behavior

  • DATETIME is not affected by time zone settings.
  • TIMESTAMP automatically adjusts based on the session or server time zone.

9. Time Zones and MySQL

9.1 Checking and Setting Time Zones

SELECT @@global.time_zone; SET time_zone = '+05:30';

9.2 Using UTC_TIMESTAMP

SELECT UTC_TIMESTAMP();

10. Indexing and Date Performance Tips

  • Create indexes on date columns used in WHERE or JOIN conditions.
  • Use date range filters instead of functions on date columns for better performance.

10.1 Avoid

SELECT * FROM orders WHERE YEAR(order_date) = 2025;

10.2 Prefer

SELECT * FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';

11. Practical Examples

11.1 Users Registered in the Last 7 Days

SELECT * FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);

11.2 Monthly Sales Summary

SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue FROM orders GROUP BY month;

11.3 Events Occurring at a Specific Time

SELECT * FROM log_events WHERE TIME(created_at) BETWEEN '09:00:00' AND '11:00:00';

MySQL offers a powerful suite of date and time data types to handle virtually any temporal data requirement. Each type—DATE, DATETIME, TIMESTAMP, TIME, and YEAR—has specific use cases depending on range, storage, and time zone handling. When working with dates and times, it is important to understand their behavior, especially with regard to time zones and automatic updates. Leveraging MySQL's rich set of functions for date manipulation allows for efficient querying and transformation of temporal data.

Related Tutorials

Frequently Asked Questions for MySQL

Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.

To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.

MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.

Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.

Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.

DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.

A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.

The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.

Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.

 A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.

 Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.

 Use the command: CREATE DATABASE database_name; to create a new MySQL database.

Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.

Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.

Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.

CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.

MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.

A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.

Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.

Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.

A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.

Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.

Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.

JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.

Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.

line

Copyrights © 2024 letsupdateskills All rights reserved