Select query for two weeks ago
Asked Answered
T

4

6

In my database table I have a field for date (varchar field to save date in yy-mm-dd format ), now I want to select records for two weeks ago. How can i do it ?

Typographer answered 6/9, 2013 at 15:21 Comment(3)
Do you mean go back two weeks and select any record that happened in that week?Silhouette
The term that you're looking for is "date arithmetic".Dania
possible duplicate of How do I select two weeks ago in MYSQL?Pyoid
P
12

Implicit date arithmetic is fairly flexible in MySQL. You can compare dates as strings without explicit use of CAST() or DATE(), but you're trusting MySQL to interpret your format correctly. Luckily for you, it will do just fine with yy-mm-dd.

I would recommend using BETWEEN and INTERVAL so that your query is easily readable; for example:

SELECT * FROM Holidays 
WHERE Date BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW();

The only trick with BETWEEN is that you have to put the lower bound first and the upper bound second; for example, if you write BETWEEN 5 AND 2, this always evaluates to FALSE because there is no value that can be greater than or equal to 5 while also being less than or equal to 2.

Here's a demo of the query in action at SQL Fiddle, and a list of the recognized INTERVAL expressions in MySQL.

Note that the parentheses around the expression NOW() - INTERVAL 14 DAY are not required but I would recommend using them here purely for the sake of clarity. It makes the predicate clause just a little bit easier to read in the absence of proper syntax highlighting, at the expense of two characters.

Pyoid answered 6/9, 2013 at 16:30 Comment(0)
B
0

Ideally you should be using date types to store dates, but being that's not the case, you should look into casting to date then comparing.

select * from yourtable where cast (yourdate as Date) BETWEEN Date_Add(CURDATE(), INTERVAL -21 Day) and Date_Add(CURDATE(), INTERVAL -14 Day)

Note, this is untested and may need a little tweaking, but should give you a general idea of what you need to do.

Also, if it's possible, you should really look into converting the varchar field to a date field....they have date types to prevent this sort of thing from happening, although i know changing field types isn't always a possibility.

Blanketing answered 6/9, 2013 at 15:31 Comment(0)
H
0

you can simply do with ADDDATE to get 14 days ago. compare string with date will work.

SELECT *
FROM your_table
WHERE your_date >= ADDDATE(NOW(), -14) AND your_date < NOW()
Hayes answered 6/9, 2013 at 15:58 Comment(2)
Note, date is stored as varchar, so cast would have to be done first.Blanketing
you can do compare date by varcharHayes
P
0

I use this for select data in past of past

SELECT * FROM Holidays 
WHERE a.dDate >= DATE( NOW( ) ) - INTERVAL 14
DAY AND a.dDate <= DATE( NOW( ) ) - INTERVAL 8
Pelaga answered 10/4, 2015 at 20:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.