Jump to content

[SOLVED] Specifying date range in query using DATE_FORMAT.


Recommended Posts

I understand that if you want to query from a daterange, this will work:

 

select * from mytable 
where 
datecol >= '2009-01-01' AND 
datecol <= '2009-09-22'

 

But when i use this query, it ignores the year and returns records that match the month and day:

select * from mytable 
where 
DATE_FORMAT(datecol, '%m-%d-%Y') >= '01-01-2009' AND
DATE_FORMAT(datecol, '%m-%d-%Y') <= '09-22-2009'

 

Anyone know the reason and can explain what's going on? Instead of dwelling too deep why, I ended up rewriting the query to use BETWEEN operator, but i just found this odd.

 

Only dates in the format YYYY-MM-DD, where the fields that make it up are ordered left to right, year (most significant digit) to day (least significant digit) can be compared using greater-than/less-than operators. This is why the DATE data type is formatted as YYYY-MM-DD. So that it can be sorted and compared correctly.

Don't do that. You're forcing your db to go through every row converting the date to a string in order to compare with a string.

 

Instead, convert your strings to dates. Then you only only have to do the conversion twice and better yet, the db can use indexes.

Something tells me that you are actually asking about a query like the following -

 

select * from mytable
where
datecol >= STR_TO_DATE('01-01-2009', '%m-%d-%Y') AND
datecol <= STR_TO_DATE('09-22-2009', '%m-%d-%Y')

 

which would actually be an efficient query that would work.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.