Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql How to use DATE_SUB in Between clause

Tags:

mysql

I am having problem while using DATE_SUB for DateTime fields. I want to use query like this:

SELECT
    * 
FROM 
    SellBySalesman 
WHERE 
    userid=37 and 
    sellingDate BETWEEN CURDATE() AND DATE_SUB(CURDATE(), INTERVAL 7 DAY)
like image 554
user1300868 Avatar asked Mar 29 '12 13:03

user1300868


People also ask

What does DATE_SUB do in MySQL?

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.

How do I insert date in YYYY MM DD format in MySQL?

Introduction to MySQL DATE data type This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want. MySQL uses 3 bytes to store a DATE value.

How do I subtract one date from another in MySQL?

DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date. Parameter: This function accepts two parameters which are illustrated below : date – Specified date to be modified. value addunit – Here the value is date or time interval to subtract.


3 Answers

I am not sure what error you are getting, but this will not work. The reason is that the arguments in your BETWEEN clause are reversed. BETWEEN requires the first argument to be the min and the second to be the max. DATE_SUB will subtract the interval from the date provided making it less than the current date.

Try something like this:

SELECT
    * 
FROM 
    SellBySalesman 
WHERE 
    userid=37 and 
    sellingDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
like image 67
Buggabill Avatar answered Oct 08 '22 19:10

Buggabill


Your BETWEEN values are backwards.

You need to have the smaller value first: "BETWEEN 1 and 10" not "BETWEEN 10 and 1".

So, in your case, you want "BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) and CURDATE()"

like image 37
D Mac Avatar answered Oct 08 '22 20:10

D Mac


You have to invert the order of between like this:

SELECT
    * 
FROM 
    SellBySalesman 
WHERE 
    userid=37 and 
    sellingDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE();
like image 43
jordeu Avatar answered Oct 08 '22 18:10

jordeu