Home >Database >Mysql Tutorial >How to Include the Upper Bound Date When Selecting Data Between Two Dates in MySQL?

How to Include the Upper Bound Date When Selecting Data Between Two Dates in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 09:16:10948browse

How to Include the Upper Bound Date When Selecting Data Between Two Dates in MySQL?

MySQL - Selecting Data Between Two Dates

Problem: Selecting data within a date range results in exclusion of the upper bound date due to the default midnight cutoff.

Query:

SELECT `users`.* FROM `users` WHERE created_at >= '2011-12-01' AND created_at <= '2011-12-06'

Solution:

To resolve this issue, there are several options:

  1. Extend the upper bound date: Change the upper bound date to include the next day:
SELECT users.* FROM users WHERE created_at >= '2011-12-01' AND created_at <= '2011-12-07'
  1. Use the DATE_ADD function: Calculate the upper bound date by adding seven days to the lower bound date:
SELECT users.* from users WHERE created_at >= '2011-12-01' AND created_at <= date_add('2011-12-01', INTERVAL 7 DAY)
  1. Use the BETWEEN operator: Specify the date range using the BETWEEN operator:
SELECT users.* from users WHERE created_at BETWEEN('2011-12-01', date_add('2011-12-01', INTERVAL 7 DAY))

These solutions all ensure that data from the specified date range, including the upper bound date, is selected.

The above is the detailed content of How to Include the Upper Bound Date When Selecting Data 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