Home > Database > Mysql Tutorial > How to Retrieve MySQL Data from the Past Week Starting on Sunday?

How to Retrieve MySQL Data from the Past Week Starting on Sunday?

Susan Sarandon
Release: 2025-01-08 16:37:40
Original
317 people have browsed it

How to Retrieve MySQL Data from the Past Week Starting on Sunday?

Extracting MySQL Data for the Last Week (Sunday Start)

This guide demonstrates how to retrieve MySQL data from the past week, beginning on the preceding Sunday. We'll leverage MySQL's date functions to achieve this.

The MySQL Query

The following query efficiently filters data to include only records from the last seven days, starting from the previous Sunday:

<code class="language-sql">SELECT id
FROM tbname
WHERE date BETWEEN date_sub(CURDATE(), INTERVAL DAYOFWEEK(CURDATE())-1 DAY) AND CURDATE();</code>
Copy after login

Detailed Explanation

  • CURDATE(): Returns the current date.
  • DAYOFWEEK(CURDATE()): Determines the day of the week (1=Sunday, 2=Monday,...,7=Saturday) for the current date.
  • INTERVAL DAYOFWEEK(CURDATE())-1 DAY: Calculates the number of days to subtract to reach the previous Sunday. If today is Sunday, it subtracts 0 days; if today is Monday, it subtracts 1 day, and so on.
  • date_sub(CURDATE(), INTERVAL DAYOFWEEK(CURDATE())-1 DAY): Subtracts the calculated number of days from the current date, resulting in the date of the previous Sunday.
  • BETWEEN ... AND CURDATE(): Selects records where the 'date' column falls within the range from the previous Sunday to the current date.

Illustrative Example

Consider this sample table:

id date
2 2011-05-14 09:17:25
5 2011-05-16 09:17:25
6 2011-05-17 09:17:25
8 2011-05-20 09:17:25
15 2011-05-22 09:17:25

Running the query above will return:

id
5
6
8

This accurately retrieves IDs (5, 6, and 8) corresponding to entries within the past week, starting from the preceding Sunday. Note that the specific results will depend on the current date when the query is executed.

The above is the detailed content of How to Retrieve MySQL Data from the Past Week Starting on Sunday?. 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