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.
| 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 |
The DATE type is used to store only date values in the format YYYY-MM-DD.
CREATE TABLE employees (
id INT,
name VARCHAR(100),
hire_date DATE
);
INSERT INTO employees (id, name, hire_date)
VALUES (1, 'Alice', '2024-05-01');
SELECT name, hire_date FROM employees;
DATETIME is used to store both date and time components in the format YYYY-MM-DD HH:MM:SS.
CREATE TABLE appointments (
id INT,
title VARCHAR(255),
appointment_time DATETIME
);
INSERT INTO appointments (id, title, appointment_time)
VALUES (1, 'Dental Checkup', '2024-07-12 14:30:00');
SELECT * FROM appointments
WHERE appointment_time BETWEEN '2024-07-01 00:00:00' AND '2024-07-31 23:59:59';
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.
CREATE TABLE log_events (
id INT,
event_description VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE documents (
id INT,
title VARCHAR(255),
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO log_events (id, event_description)
VALUES (1, 'Server started');
SELECT * FROM log_events;
The TIME type is used to store time intervals or times of day in HH:MM:SS format.
CREATE TABLE work_shifts (
id INT,
shift_name VARCHAR(50),
duration TIME
);
INSERT INTO work_shifts (id, shift_name, duration)
VALUES (1, 'Morning Shift', '08:00:00');
Stores a four-digit year value.
CREATE TABLE car_models (
id INT,
model_name VARCHAR(50),
model_year YEAR
);
INSERT INTO car_models (id, model_name, model_year)
VALUES (1, 'Tesla Model S', 2025);
SELECT CURRENT_DATE;
SELECT CURRENT_TIME;
SELECT NOW();
SELECT DATE_ADD('2025-01-01', INTERVAL 10 DAY);
SELECT DATE_SUB('2025-01-01', INTERVAL 1 MONTH);
SELECT DATEDIFF('2025-01-10', '2025-01-01');
SELECT TIMEDIFF('12:30:00', '08:00:00');
SELECT EXTRACT(YEAR FROM '2025-07-12');
SELECT DATE_FORMAT(NOW(), '%W, %M %d, %Y');
SELECT STR_TO_DATE('12-07-2025', '%d-%m-%Y');
SELECT TIME_FORMAT('13:45:00', '%h:%i %p');
SELECT @@global.time_zone;
SET time_zone = '+05:30';
SELECT UTC_TIMESTAMP();
SELECT * FROM orders WHERE YEAR(order_date) = 2025;
SELECT * FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';
SELECT * FROM users
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue
FROM orders
GROUP BY month;
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.
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.
Copyrights © 2024 letsupdateskills All rights reserved