Home >Database >Mysql Tutorial >How to Correctly Query Between Two Dates in MySQL?

How to Correctly Query Between Two Dates in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-21 17:57:13698browse

How to Correctly Query Between Two Dates in MySQL?

MySQL date range query skills

When querying date ranges efficiently in MySQL, date order is crucial. The following query statement:

<code class="language-sql">SELECT * FROM `objects` 
WHERE (date_field BETWEEN '2010-09-29 10:15:55' AND '2010-01-30 14:15:55')</code>

No results will be returned because the second date is earlier than the first, making the date range invalid.

Solution:

To fix this, reverse the order of the dates in the query:

<code class="language-sql">SELECT *
FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')</code>

This query will correctly query the date range between January 30, 2010 and September 29, 2010 and return the desired results.

Official documentation:

For more details on datetime usage in MySQL, please refer to the official documentation: https://www.php.cn/link/4c74dcfeac90df69aed5c8a90125e696

The above is the detailed content of How to Correctly Query Between Two Dates in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn