0

I have a query:

SELECT ... FROM orders WHERE date_created BETWEEN '2012-07-30' AND '2012-07-30' 

It returns 0 results, although there's 1000+ entries for date 2012-07-30. I found out that the BETWEEN simply does not grab the END date, so if it was

BETWEEN '2012-07-28' AND '2012-07-30' 

...it should grab me entries for 28, 29 but not 30.

How can I make it to take the end date itself too?

2
  • why don't you simply use WHERE date_created= '2012-07-30' Commented Jul 31, 2012 at 23:26
  • this might sound stupid, but can't you add a day in the "end" date? Like BETWEEN '2012-07-28' AND '2012-07-31' Commented Jul 31, 2012 at 23:27

5 Answers 5

2

Tell it the end of the day instead of the beginning.

'2012-07-30 23:59:59' 
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer, so that was why!
2

Never use BETWEEN with dates (and especially with datetimes). You can use:

WHERE date_created >= '2012-07-30' AND date_created < '2012-07-31' ---or: < '2012-07-30' + INTERVAL 1 DAY -------------------^-------------- notice the lack of the equal sign here 

which works equally well with DATE, DATETIME and TIMESTAMP datatypes.

Notice that you may still miss some rows with the proposed solution of BETWEEN '2012-07-30' AND '2012-07-30 23:59:59'.

For detailed explanations, read this nice blog post:

What do BETWEEN and the devil have in common?

The blog discusses SQL-Server issues but most parts about BETWEEN apply to MySQL as well (except for the not yet existing milli-second support, thanx @Ignacio for the correction).

2 Comments

An excellent point in general, but slightly less relevant with MySQL.
@Ignacio: Yes, you are right in that. But it's good to have code that will not break when millisecond support will be added.
0

Add a day to the end date in your query:

 BETWEEN('2012-07-28', DATE_ADD('2012-07-30', INTERVAL 1 DAY) 

Comments

0

why don't you simply use

... WHERE date_created= '2012-07-30'

Comments

0

Just to add more info between do exactly this (min <= expr AND expr <= max) ,got it from here

as others pointed out, you missed the time, and its better be a timestamp unless the date is used for things like birthdate

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.