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)
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!