Home >Database >Mysql Tutorial >How to Select Rows from the Previous Month in MySQL?

How to Select Rows from the Previous Month in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 19:04:12900browse

How to Select Rows from the Previous Month in MySQL?

Selecting Rows from the Previous Month

Database queries often require retrieving data based on specific criteria, such as selecting rows that belong to a particular time period. For instance, you may need to fetch all records within the current month or those from the previous month. Let's explore a query to accomplish the latter.

Querying for Last Month's Rows

To retrieve rows created in the previous month, the following MySQL query can be utilized:

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

Understanding the Query:

  • YEAR(date_created) extracts the year component from the date_created column.
  • CURRENT_DATE - INTERVAL 1 MONTH subtracts one month from the current date to obtain the first day of the previous month.
  • YEAR() and MONTH() functions extract the year and month components from this modified date.
  • These values are then compared with the year and month components of the date_created column to check if the row was created in the previous month.

By utilizing this query, you can effectively select rows that were created in the previous month, regardless of the current month. This versatile approach is useful for various data analysis and reporting tasks.

The above is the detailed content of How to Select Rows from the Previous Month 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