3

I have a database table with date field whose data type is also date and i want to fetch those recods which lie betwnn two dates.

My query is :

SELECT * FROM wp_races_entry  WHERE date_in >=2012-02-08 && date_in<=2012-02-27

i also tried

SELECT * FROM wp_races_entry WHERE date_in  BETWEEN 2012-02-08 AND 2012-02-27

i have records in table with date 2012-02-14 but still it return empty value.

Please help me guiding what i am missing exactly.

4
  • Are you missing quotes? 2012-02-08 == 2002 Commented Mar 15, 2012 at 12:35
  • Any chance you could show us your table's field list and data types? And a few of the rows, some in the date range and some not. Also, if you just do SELECT * FROM wp_races_entry do you get all rows back as expected? (Should SQL dates not be formatted as #yyyy mm dd#?) Commented Mar 15, 2012 at 12:36
  • 1
    @JTeagle - Different flavours of SQL have different ways of representing date data-types. One thing that is reasonably universal is to use a string data-type and allow it to be implicitly converted to a date data-type. That has it's own pitfalls ('01-Jan-2012' won't work in France, etc), but '20120101' is pretty common practice Commented Mar 15, 2012 at 12:44
  • @Dems - Thanks - valuable information, I did not know this. Commented Mar 15, 2012 at 12:52

3 Answers 3

5

You need quotes round your dates:

SELECT * FROM wp_races_entry WHERE date_in BETWEEN '2012-02-08' AND '2012-02-27'

Without the quotes your dates are treated as arithmetic expressions: 2012-02-08 = 2002.

The query you posted is equivalent to this:

SELECT * FROM wp_races_entry WHERE date_in BETWEEN 2002 AND 1983
Sign up to request clarification or add additional context in comments.

Comments

5

2012-02-08 isn't a date, it's an integer calulation that yield the result 2002. This is then implictly cast into a date, with 2002 meaning 2002 days from the base date

Instead, use '2012-02-08' which is a string, which is also implicitly cast into a date, but the one you want.

SELECT * FROM wp_races_entry WHERE date_in BETWEEN '2012-02-08' AND '2012-02-27'

Comments

1

Try:

SELECT * FROM wp_races_entry WHERE date_in>= '2012-02-08 00:00:00' and date_in<= '2012-02-27 00:00:00'

2 Comments

it's a DATE field, not a DATETIME field. Therefore false.
And the OPs >= and <= have spontaneously changed to > and < for no apparent reason.

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.