Home >Database >Mysql Tutorial >How to Limit MySQL Queries to the Last 30 Days?

How to Limit MySQL Queries to the Last 30 Days?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 03:32:09922browse

How to Limit MySQL Queries to the Last 30 Days?

MySQL Query: Limiting Records to Last 30 Days

This article will guide you in writing a MySQL query to retrieve records added within the last 30 days.

The issue arises when applying the DATE_FORMAT function to the WHERE clause, which selects all records instead of limiting them to the specified period.

To resolve this, the correct syntax is:

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

It's crucial to apply DATE_FORMAT in the SELECT clause. Additionally, ensure that the create_date is stored as a DATE and not as DATETIME. If stored as DATETIME, use NOW() instead of CURDATE():

SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

By following these adjustments, you can effectively limit your query to the last 30 days and retrieve the desired records.

The above is the detailed content of How to Limit MySQL Queries to the Last 30 Days?. 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