I have this simple query:
select sm.id, h.time
from main_data sm
INNER JOIN TA t on t.id = sm.id AND t.first=1
LEFT OUTER JOIN History h on h.id= sm.id
WHERE trunc(TO_DATE(h.time, 'DD-MM-YYYY')) BETWEEN trunc(TO_DATE('07.05.2015', 'DD.MM.YYYY')) AND trunc(TO_DATE('07.06.2015', 'DD.MM.YYYY'));
h.time
looks like 07-MAY-15
The above query returns no results, even if there are dates between the specified parameters. BUT if I change the where clause to
WHERE trunc(TO_DATE(h.time, 'DD-MM-YYYY')) BETWEEN trunc(TO_DATE('07.05.15', 'DD-MM-YYYY')) AND trunc(TO_DATE('07.06.15', 'DD-MM-YYYY'))
- the same dates but instead of 2015
there is just 15
I can see the results of the query.
The problem is that I'm expecting the user to enter a full year - not just 15
. How can I avoid this mismatch?
First, your date comparison is too complicated. If
h.time
is an internal date format (which it should be), then just do:Another very important issue with your query is that the
WHERE
clause is turning theLEFT JOIN
into anINNER JOIN
. Either change the join type to be consistent with the logic or move theWHERE
to theON
clause (you will then get results even when there are no matching dates.