133

Hi I have a table with a date field and some other information. I want to select all entries from the past week, (week start from Sunday).

table values:

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

I want to select all ids from last week, expected output is 5, 6, 8. (id 2 not in last week, and id 15 is in current week.)

How to write and SQL Query for the same.

5
  • So just to clarify, you want data since sunday, not necessarily 7 days of data? So if today is Monday you'll get 2 days of data (Sunday and Monday)? Commented May 22, 2011 at 18:44
  • Sunday to Saturday. Not last 7 days Commented May 22, 2011 at 18:48
  • I don't feel like actually converting this to SQL right now, but you can find an algorithm to determine the day of the week on Wikipedia, and then use that to decide how far back to look: en.wikipedia.org/wiki/… Commented May 22, 2011 at 18:55
  • @Brendan Long: he could use SELECT id FROM tbl WHERE WEEK(date, 0) = WEEK(NOW(), 0) - 1 for weeks, but I guess his target is not real calendar weeks. At least he didn't mention s/t like ISO-8601, or whether he wants turn of the year to be taken into consideration. Commented May 22, 2011 at 19:14
  • 4
    For me answer is WHERE table.column >= DATE(NOW()) - INTERVAL 7 DAY Commented Jul 3, 2019 at 16:05

23 Answers 23

168
select id from tbname
where date between date_sub(now(),INTERVAL 1 WEEK) and now();
Sign up to request clarification or add additional context in comments.

2 Comments

This does not solve OP question if you ran this on '2011-05-22' you would get id 15...
This is the best answer.
131
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY

3 Comments

Hi, How to get last week with week defined start from Monday to Sunday
@Graph Yes, The SQL script above will be like that: SELECT id FROM tbl WHERE DATE > DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY) AND DATE <= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY)
it returns last 7 days instead of last week
40
SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)

I use the YEARWEEK function specifically to go back to the prior whole calendar week (as opposed to 7 days before today). YEARWEEK also allows a second argument that will set the start of the week or determine how the first/last week of the year are handled. YEARWEEK lets you to keep the number of weeks to go back/forward in a single variable, and will not include the same week number from prior/future years, and it's far shorter than most of the other answers on here.

3 Comments

Near as I can tell, this is the only answer that actually answers the OPs question correctly. The question was how to get records from the previous week. Many of the answers here are actually incorrect.
If you want to specify start day of the week as well, supply 2nd argument to YEARWEEK(): WHERE YEARWEEK(dateColumnFromTbl, 1) = YEARWEEK(CURDATE() - INTERVAL 1 WEEK, 1)
if i want to include the today's date as well... inside that last week...how was that?
14

Simplified form:

Last week data:

SELECT id FROM tbl


WHERE 
WEEK (date) = WEEK( current_date ) - 1 AND YEAR( date) = YEAR( current_date );

2 weeks ago data:

SELECT id FROM tbl


WHERE 
WEEK (date) = WEEK( current_date ) - 2 AND YEAR( date) = YEAR( current_date );

SQL Fiddle

http://sqlfiddle.com/#!8/6fa6e/2

3 Comments

What happens in the first week of the year?
The question was to select data from last week? If first week of the year, and you want to select last week data, the query will return last week of the previous year.
I'm just confused by the YEAR(date) = YEAR(current_date) then. How can that select the previous year?
11

If you're looking to retrieve records within the last 7 days, you can use the snippet below:

SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;

Comments

9

You can make your calculation in php and then add it to your query:

$date = date('Y-m-d H:i:s',time()-(7*86400)); // 7 days ago

$sql = "SELECT * FROM table WHERE date <='$date' ";

now this will give the date for a week ago

Comments

6

Probably the most simple way would be:

SELECT id
FROM table
WHERE date >= current_date - 7

For 8 days (i.e. Monday - Monday)

Comments

6

PLEASE people... 'Last week' like the OP asked and where I was looking for (but found none of answers satisfying) is THE LAST WEEK.

If today is Tuesday, then LAST WEEK is Monday A WEEK AGO to Sunday A WEEK AGO.

So:

WHERE
    WEEK(yourdate) = WEEK(NOW()) - 1

Or for ISO weeks:

WHERE
    WEEK(yourdate, 3) = WEEK(NOW(), 3) - 1

2 Comments

Just be careful with this if you have more than 1 year of data as it will show you all of the same week for those previous years as well.
Absolutely true, but that goes for pretty much all answers here. It would indeed require a GROUP BY or something similar.
5

Here is a way to get last week, month, and year records in MySQL.

Last Week

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE WEEK(InsertTime) = WEEK(NOW()) - 1
AND MONTH(InsertTime) = MONTH(NOW())
AND YEAR(InsertTime) = YEAR(NOW()) 

Last Month

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE MONTH(InsertTime) = MONTH(NOW()) - 1
AND YEAR(InsertTime) = YEAR(NOW()) 

Last YEAR

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE YEAR(InsertTime) = YEAR(NOW()) - 1;

3 Comments

can we use all three in one query? in sub queries?
Not quite. For an example, speaking of month section, the code above would calculate a MONTH = 0, if "InsertTime" is in January. But, something like "WHERE MONTH(InsertTime) = MONTH(NOW() - INTERVAL 1 MONTH)" should work properly.
This only work for dates within same year. Not a generic solution.
3

You'll need to calc which day relative to today is Sunday in your middleware (php, python, etc.)*

Then,

select id
from table
where date >= "$sunday-date" + interval 7 DAY
  • may be a way to get sunday's date relative to today in MySQL as well; that would be arguably the cleaner solution if not too expensive to perform

Comments

3

It can be in a single line:

SELECT * FROM table WHERE Date BETWEEN (NOW() - INTERVAL 7 DAY) AND NOW()

Comments

2

A simple way can be this one, this is a real example from my code and works perfectly:

where("actions.created_at >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)")

Comments

1

The above query will not work. After the where clause, if we can not CAST the column value, then it will not work. You should cast the column value.

e.g.:

SELECT.....
WHERE CAST( yourDateColumn AS DATE ) > DATEADD( DAY, -7, CAST( GETDATE() AS DATE )

Comments

0
SELECT id  FROM tb1
WHERE 
YEARWEEK (date) = YEARWEEK( current_date -interval 1 week ) 

1 Comment

Please explain why your code answers the asker's question.
0

I often do a quick "last week" check as well and the following tends to work well for me and includes today.

DECLARE @StartDate DATETIME 
DECLARE @EndDate DATETIME 

SET @StartDate = Getdate() - 7 /* Seven Days Earlier */
SET @EndDate = Getdate() /* Now */

SELECT id 
FROM   mytable 
WHERE  date BETWEEN @StartDate AND @Enddate 

If you want this to NOT include today just subtract an extra day from the @EndDate. If I select these two variables today get

@StartDate 2015-11-16 16:34:05.347 /* Last Monday */

@EndDate 2015-11-23 16:34:05.347 /* This Monday */

If I wanted Sunday to Sunday I would have the following.

SET @StartDate = Getdate() - 8 /* Eight Days Earlier */
SET @EndDate = Getdate() - 1  /* Yesterday */

@StartDate 2015-11-15 16:34:05.347 /* Previous Sunday */

@EndDate 2015-11-22 16:34:05.347 /* Last Sunday */

Comments

0
WHERE yourDateColumn > DATEADD(DAY, -7, GETDATE()) ;

Comments

0

You can also use it esay way

SELECT *
FROM   inventory
WHERE  YEARWEEK(`modify`, 1) = YEARWEEK(CURDATE(), 1)

Comments

0

i Use this for the week start from SUNDAY:

SELECT id FROM tbl
WHERE
date >= curdate() - INTERVAL DAYOFWEEK(curdate())+5 DAY  
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-2 DAY

Comments

0

try this

WHERE trunc(DATE) <= (trunc (sysdate) -5)  AND trunc(DATE) >= (trunc (sysdate) -12)

-5 is 5 days back from system date ,, -12 is 12 days back from system date for this example wednesday / or sednesday to wednesday cant recall.

Comments

0

My way:

SELECT id
FROM tablename
WHERE date BETWEEN DATE_ADD(NOW(), INTERVAL -1 WEEK) AND NOW()

Comments

-1

Try this:

Declare @Daytype varchar(15),
        @StartDate datetime,
        @EndDate datetime
set @Daytype = datename(dw, getdate())

if @Daytype= 'Monday' 
    begin
        set @StartDate = getdate()-7 
        set @EndDate = getdate()-1

    end


else if @Daytype = 'Tuesday'

    begin
        set @StartDate = getdate()-8 
        set @EndDate = getdate()-2

    end
Else if @Daytype = 'Wednesday'
    begin
        set @StartDate = getdate()-9
        set @EndDate = getdate()-3
    end
Else if @Daytype = 'Thursday'
    begin
        set @StartDate = getdate()-10 
        set @EndDate = getdate()-4
    end

Else if @Daytype = 'Friday'

    begin
        set @StartDate = getdate()-11
        set @EndDate = getdate()-5

    end

Else if @Daytype = 'Saturday'

    begin
        set @StartDate = getdate()-12
        set @EndDate = getdate()-6

    end

Else if @Daytype = 'Sunday'

    begin
        set @StartDate = getdate()-13
        set @EndDate = getdate()-7

    end

 select @StartDate,@EndDate

Comments

-2

You can try this one. it worked for me :

where date(createdtime) <= date(curdate())-7

In the the above code createdtime is database field name, as individuals this name could vary.

2 Comments

Share code snippet from any mysql editor. This way without formatting and code highlight it's not clear.
It selects previous dates, so does exactly opposite than requested. Also date(curdate()) does nothing meaningful compared to simple curdate().
-6

If you already know the dates then you can simply use between, like this:

SELECT id    
FROM `Mytable`    
where MyDate BETWEEN "2011-05-15" AND "2011-05-21"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.