4

I've been searching on how to do this but am not coming up with a clear answer (maybe my resources are not that good). I need to make a SQLite query to retrieve data between two dates from a SQLite DB.

I am trying this:

SELECT CONTACTNAME
FROM SHIPMENT 
WHERE DATECREATED 
BETWEEN date('11-15-2010') 
AND date('12-25-2010');

The data is in my SQLite DB as:

CONTACTNAME=VARCHAR
DATECREATED=date (format: "11/22/2010")
0

3 Answers 3

16

SQLite does not have a date type. You can get by with storing dates as strings, but you need to use YYYY-MM-DD date order, NOT MM-DD-YYYY. There are two major reasons for this:

(1) Correct ordering

With YYYY-MM-DD dates, the lexicographical order is the same as the chronological order, which makes the <, >, and BETWEEN operators work as expected.

This is not the case for MM-DD-YYYY dates. A query for dates BETWEEN '11-15-2010' AND '12-25-2010' will falsely match '11-22-1963' and '12-21-2012'.

(2) Compatibility with SQLite date and time functions.

They accept both string and numeric (Julian) dates, but if you pass a string to any of these functions, it has to have YYYY-MM-DD order.

4

Try just removing date():

SELECT CONTACTNAME
FROM SHIPMENT 
WHERE DATECREATED 
BETWEEN '2010-11-15' 
AND '2010-12-25'
4
  • ah ok thanks, not sure why the tutorial I read had that in there
    – Rick
    Dec 15, 2010 at 18:11
  • @dan04, can you clarify "that"? I tried the code I used above on my own SQLite DB, with MM-DD-YYYY order, so am wondering if you are referring to date() or if there are differences in versions of SQLite that might be relevant to others reading this question :) Dec 16, 2010 at 20:58
  • 1
    it works correctly only at yyyy-MM-dd format. Just see dan04's answer. Jan 8, 2011 at 6:40
  • 1
    Thanks for the corrections, how embarrassing . . . unfortunately, I don't seem to be able to delete my post because it was accepted :-( Any more experiences SO users know how to get this fixed? Jan 24, 2011 at 22:23
2
SELECT field_1,field_2,date_field
 WHERE julianday(date_field)
 BETWEEN julianday('1998-01-01') and julianday('2008-01-01');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.