Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Get the first and last day of previous week

Tags:

sql

mysql

I am trying to get the first and last day of the previous week in MySQL, where the first and last days are Monday and Sunday, respectively.

For example if today (March 1, 2017) is when the SQL is executed I would like to obtain:

  • FirstDay --> Feb 20
  • LastDay --> Feb 26

I have tried the following and all sorts of variations with this, without success.

SELECT DATE_ADD(curdate(), INTERVAL(-WEEKDAY(curdate())) DAY); 

Is it possible to achieve these results when executed anytime within the current week?

like image 558
choloboy Avatar asked Sep 19 '25 15:09

choloboy


1 Answers

Selecting first and last day of previous week:

SELECT
 (curdate() - INTERVAL((WEEKDAY(curdate()))+1) DAY) as e,
 (curdate() - INTERVAL((WEEKDAY(curdate()))+7) DAY) as s

s: 2017-02-20

e: 2017-02-26

And if you want filter last week table rows:

SELECT * FROM tblName
WHERE dateCol >= (curdate() - INTERVAL((WEEKDAY(curdate()))+7) DAY)
  AND dateCol < (curdate() - INTERVAL((WEEKDAY(curdate()))+1) DAY)
ORDER BY dateCol DESC -- or ASC
like image 186
MohaMad Avatar answered Sep 22 '25 08:09

MohaMad