4

I'm getting some strange results from using BETWEEN in my sql query. Wondering if anyone can help me to understand why i am getting these results.

I'm searching a date range in the format of dd/mm/yyyy. So i want to select all entries within a certain date range.

$dbSearchRecords_result = "SELECT * FROM $tbl_name WHERE Date BETWEEN '$DateFrom_order' AND '$DateTo_order'";

$dbSearchRecords_result = mysql_query($dbSearchRecords_result);

I am then calling the results in a while statement from an array

while ($row = mysql_fetch_array($dbSearchRecords_result)){

Now if I search BETWEEN 12/02/2011 14/02/2011 there is a date returned from 13/12/2010.

Yet if I search 12/02/2011 13/02/201 I do not get the result of 13/12/2010.

Any ideas would be most appreciated.

Thanks.

3
  • 1
    Are you sure your date variables are actually formatted as proper dates? Commented Feb 4, 2011 at 10:54
  • Have you checked that the generated SQL statement from PHP is what you expected? Commented Feb 4, 2011 at 10:55
  • @ KeenLearner. I've only just realized that which is pretty silly of me. I'm pretty sure that is the main issue. Thanks mate. Commented Feb 4, 2011 at 10:59

3 Answers 3

7

The BETWEENoperator is most likely reading your ranges as strings. From the book:

For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

So, try:

SELECT * FROM `mytable` 
WHERE `date` BETWEEN CAST('2011-01-02' AS DATE) AND CAST('2011-12-02' AS DATE)
Sign up to request clarification or add additional context in comments.

Comments

5

MySQL's needs values in this format to do a proper comparison:

YYYY-MM-DD

you could use STR_TO_DATE to convert your string into the right format.

Plus obviously, the Date field needs to be of the DATE or DATETIME type.

Comments

1

try to format the values as DATE.. as in

$dbSearchRecords_result = "SELECT * FROM $tbl_name WHERE Date BETWEEN DATE('$DateFrom_order') AND DATE('$DateTo_order')";

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.