Home > Database > Mysql Tutorial > How Can I Retrieve Data from the Previous Month Using SQL?

How Can I Retrieve Data from the Previous Month Using SQL?

DDD
Release: 2024-12-10 05:07:15
Original
208 people have browsed it

How Can I Retrieve Data from the Previous Month Using SQL?

Retrieving Data from a Specific Month Using SQL

In relational databases, it's often necessary to retrieve data created within a specific time frame. One frequent requirement is querying rows created in the previous month. This article explains a simple SQL query to accomplish this task.

The provided query focuses on a table containing a date_created column that records the date and time when each row was created. By leveraging SQL functions that extract date components, we can narrow down the selection to rows created within the previous month:

SELECT *
FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
Copy after login

This query uses the CURRENT_DATE function to determine the current date. The INTERVAL 1 MONTH expression subtracts one month from this date, providing a reference point for selecting rows created within the previous month.

The YEAR and MONTH functions extract the corresponding components from the date_created column. By comparing these values to the adjusted current date, the query identifies rows whose creation dates fall within the correct month.

The above is the detailed content of How Can I Retrieve Data from the Previous Month Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template