Home > Database > Mysql Tutorial > How to Retrieve Data from the Previous Month in MySQL?

How to Retrieve Data from the Previous Month in MySQL?

Linda Hamilton
Release: 2024-12-06 10:15:13
Original
467 people have browsed it

How to Retrieve Data from the Previous Month in MySQL?

Retrieving Data from the Previous Month

This query retrieves all rows from a database that were created in the previous month. The query utilizes the MySQL CURRENT_DATE function to dynamically determine the current month and subtracts one month to target the previous month.

Query Explanation:

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

Breakdown:

  • SELECT * retrieves all columns from the specified table.
  • FROM table indicates the table to query.
  • WHERE clause filters the results based on the specified conditions:

    • YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) ensures that the row's year matches the year of the previous month.
    • MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) checks that the row's month matches the month of the previous month.

Example:

If the current date is January 15th, 2023, the query will retrieve all rows from the "table" that were created in December 2022.

The above is the detailed content of How to Retrieve Data from the Previous Month in MySQL?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template