0

Here's the thing - I'm saving date in database as string in format dd/mm/yyyy. I want to get rows in which date is between two dates - let's say 11/07/2009 and 29/08/2014, how to do that?

I tried

SELECT * FROM attr WHERE time_added between '11/7/2009' AND '29/8/2014' 

but it's not working correctly. Any great would be great?

7
  • Yeah, if you saved dates as dates that'd be great. Commented Jul 6, 2014 at 21:40
  • But is it possible to do it this way? Commented Jul 6, 2014 at 21:41
  • Why do you store data as strings at first place? Commented Jul 6, 2014 at 21:42
  • 1
    @TheCrafter: well, you could convert them in runtime, without any SPs directly in a query. Commented Jul 6, 2014 at 21:45
  • You could use STR_TO_DATE(time_added, '%d/%m/%Y') to convert your string to date type, but MySQL won't use an index for the query, see dev.mysql.com/doc/refman/5.6/en/… . Commented Jul 6, 2014 at 21:46

1 Answer 1

1

First of all, it is recommended to use the MySQL's DATE type for dates, selecting the date range would be easy and efficient. But if you have your own reason to use string type (like you are working with a specific calender and you don't have the converter), then you should consider followings:

  • you told that you are using the dd/mm/yyyy format for dates but in your code you wrote 11/7/2009 which should be 11/07/2009
  • In order to select range you should save your date like yyyy/mm/dd, specially when you put index on this filed, it will be high performance.
  • You need not to save format charterers like '/' in database. you can format the output later and show the date in any order and format you want.

As the result I offer you the following solution:

Use the YYYYMMDD format to save the date. the select query will be something like:

SELECT *, DATE_FORMAT(time_added, '%d/%m/%Y') AS time_added2 FROM attr 
WHERE time_added between '20090711' AND '20140829';

As and alternative if you can not change the database, then the following query will work on the existing database (date saved in dd/mm/yyyy format):

SELECT * FROM attr WHERE 
CONCAT(SUBSTR(time_added, 7, 4), SUBSTR(time_added, 4, 2), SUBSTR(time_added, 1, 2)) 
BETWEEN '20090711' AND '20140829';
Sign up to request clarification or add additional context in comments.

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.