MySQL Date Comparison: Best Queries & Performance Tips

1. Introduction

Handling dates in MySQL is extremely important among database operations. For example, in scenarios where you aggregate sales data by date or search records from a specific past period, date comparison is essential. In this article, we will thoroughly explain everything from the basics of MySQL date manipulation and comparison to advanced examples and even how to optimize performance. We aim to provide content that is useful for users of all levels, from beginners to intermediate.

2. Overview of MySQL Date Data Types

Types and Characteristics of Date Data Types

MySQL provides three main date data types. Below is a brief explanation of each.
  1. DATE
  • Stored value: year, month, and day (YYYY-MM-DD)
  • Feature: Since it does not include time information, it is suitable for managing simple dates.
  • Examples: birthdays, deadlines.
  1. DATETIME
  • Stored value: year, month, day, and time (YYYY-MM-DD HH:MM:SS)
  • Feature: Because it includes time information, it is suitable for recording precise timestamps.
  • Examples: creation timestamp, last update timestamp.
  1. TIMESTAMP
  • Stored value: year, month, day, and time (YYYY-MM-DD HH:MM:SS)
  • Feature: Because it is timezone-dependent, it is convenient for managing dates and times across different regions.
  • Examples: log data, transaction records.

Guidelines for Choosing the Appropriate Data Type

  • If you don’t need time, choose DATE.
  • If you need time, select DATETIME or TIMESTAMP based on your application’s timezone requirements.

Sample Query

Below are examples for each data type.
CREATE TABLE events (
    event_id INT AUTO_INCREMENT PRIMARY KEY,
    event_date DATE,
    event_datetime DATETIME,
    event_timestamp TIMESTAMP
);

3. How to Compare Dates

How to Use Basic Comparison Operators

In MySQL, the following operators are used for date comparisons.
  1. = (equal)
  • Retrieves data that matches the specified date.
   SELECT * FROM events WHERE event_date = '2025-01-01';
  1. > / < (greater than / less than)
  • Searches for data before or after the specified date.
   SELECT * FROM events WHERE event_date > '2025-01-01';
  1. <= / >= (less than or equal / greater than or equal)
  • Searches for a range that includes the specified date.
   SELECT * FROM events WHERE event_date <= '2025-01-10';

Range Search Using BETWEEN

BETWEEN operator makes it easy to specify dates within a specific range.
SELECT * FROM events 
WHERE event_date BETWEEN '2025-01-01' AND '2025-01-31';
Note:
  • BETWEEN includes both the start and end values of the range, so make sure no data within the range is missed.

4. How to Calculate Date Differences

How to Use the DATEDIFF Function

DATEDIFF() Using this function, you can calculate the difference (in days) between two dates.
SELECT DATEDIFF('2025-01-10', '2025-01-01') AS days_difference;
Result:
  • 9 days

Using the TIMESTAMPDIFF Function

TIMESTAMPDIFF() allows you to calculate the difference in any unit such as years, months, days, or hours.
SELECT TIMESTAMPDIFF(MONTH, '2025-01-01', '2025-12-31') AS months_difference;
Result:
  • 11 months

5. Date Addition and Subtraction

Date Manipulation Using the INTERVAL Clause

In MySQL, you can easily add or subtract dates by using the INTERVAL clause. This allows you to create queries that retrieve dates a certain period before or after a given date.

Date Addition

Example of adding a date using INTERVAL.
SELECT DATE_ADD('2025-01-01', INTERVAL 7 DAY) AS plus_seven_days;
Result: 2025-01-08

Date Subtraction

Subtracting a date using INTERVAL works similarly.
SELECT DATE_SUB('2025-01-01', INTERVAL 1 MONTH) AS minus_one_month;
Result: 2024-12-01

Example Use: Reminder System

Below is a query example that retrieves events occurring 7 days before for automatically sending reminder notifications.
SELECT event_name, event_date 
FROM events 
WHERE event_date = DATE_SUB(CURDATE(), INTERVAL 7 DAY);

Calculations Based on the Current Date

  • CURDATE(): Returns the current date (YYYY-MM-DD).
  • NOW(): Returns the current date and time (YYYY-MM-DD HH:MM:SS).
Example: Calculate the date one week from today.
SELECT DATE_ADD(CURDATE(), INTERVAL 7 DAY) AS next_week;

6. Practical Query Examples

Retrieve records for a specific date

Retrieve events that correspond to the specified date.
SELECT * 
FROM events 
WHERE event_date = '2025-01-01';

Extract data within a date range

An example that searches for events within a one-week range.
SELECT * 
FROM events 
WHERE event_date BETWEEN '2025-01-01' AND '2025-01-07';

Aggregation based on dates

A query that aggregates how many events are registered per month.
SELECT MONTH(event_date) AS event_month, COUNT(*) AS total_events 
FROM events 
GROUP BY MONTH(event_date);
Example result:
event_monthtotal_events
110
215

7. Performance Optimization

Efficient Searching Using Indexes

Setting an index on the date column dramatically improves search speed.

Creating an Index

The following is the SQL to create an index on the event_date column.
CREATE INDEX idx_event_date ON events(event_date);

Verifying the Effect of the Index

You can use EXPLAIN to view the query execution plan.
EXPLAIN SELECT * 
FROM events 
WHERE event_date = '2025-01-01';

Cautions When Using Functions

Using functions in the WHERE clause can render the index ineffective.

Bad Example

In the following query, the DATE() function prevents the index from being used.
SELECT * 
FROM events 
WHERE DATE(event_date) = '2025-01-01';

Improved Example

It is recommended to compare directly without using functions.
SELECT * 
FROM events 
WHERE event_date >= '2025-01-01' 
  AND event_date < '2025-01-02';

8. FAQ (Frequently Asked Questions)

Q1: What is the difference between DATE and DATETIME types?

  • A1:
  • DATE type: Stores only the date (YYYY-MM-DD). Use when time information is not needed.
  • DATETIME type: Stores date and time (YYYY-MM-DD HH:MM:SS). Use when the exact timing of events is required.
Example:
CREATE TABLE examples (
    example_date DATE,
    example_datetime DATETIME
);

Q2: What should you watch out for when specifying a date range with BETWEEN?

  • A2:
  • BETWEEN includes both the start and end dates, so if the end date has no time set, you may not retrieve the intended data.
Example:
-- This query may not retrieve data for "2025-01-01 23:59:59"
SELECT * 
FROM events 
WHERE event_date BETWEEN '2025-01-01' AND '2025-01-31';
Improvement: Set the end date to 23:59:59 explicitly, or perform a comparison that ignores the time.
SELECT * 
FROM events 
WHERE event_date >= '2025-01-01' AND event_date < '2025-02-01';

Q3: How do you handle time zone differences?

  • A3: MySQL’s TIMESTAMP type is time zone–aware. In contrast, the DATETIME type is stored as a fixed value and is not affected by time zones.
Example of checking time zone settings:
SHOW VARIABLES LIKE 'time_zone';
Example of changing the time zone:
SET time_zone = '+09:00'; -- Japan Standard Time (JST)

Q4: How can you retrieve data from the past 30 days?

  • A4: CURDATE() or NOW() combined with INTERVAL can be used to retrieve data from the past 30 days.
Example:
SELECT * 
FROM events 
WHERE event_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);

Q5: How can you improve the performance of date comparisons?

  • A5:
  • Create an index: Set an index on the date column.
  • Avoid using functions: Using functions in the WHERE clause can disable indexes, so use direct comparisons.

9. Summary

Key Points

In this article, we explained date manipulation and comparison methods in MySQL in detail. The key points are as follows.
  1. Characteristics and appropriate use of date data types (DATE, DATETIME, TIMESTAMP).
  2. Basic comparison operators (=, >, <, BETWEEN, etc.).
  3. Methods for calculating date differences (DATEDIFF(), TIMESTAMPDIFF()).
  4. Using indexes and optimal query design to improve performance.
We hope that through this article you’ll become proficient at efficiently handling dates in MySQL and crafting practical queries.