Skip to Main Content
  • Questions
  • concatenate dates to get data in a specific date\time range

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Jagannatha.

Asked: August 31, 2017 - 2:04 am UTC

Last updated: July 25, 2019 - 2:35 am UTC

Version: 12c

Viewed 10K+ times! This question is

You Asked

OK - I have been asked to write a report that captures activity between 17:00 and 08:00 the next day.

So when the query will run the next day we need to look back to sysdate -1 || 17:00

I was thinking to use

Select *
from table
where date_field between TO_DATE(trunc(sysdate -1) || '17:00'), 'DD/MM/YYYY HH:Mi')
AND TO_DATE(trunc(sysdate) || '08:00'), 'DD/MM/YYYY HH:Mi')

But I keep getting ORA-01858: a non-numeric character was found where a numeric was expected.

I am not sure what is causing this, unless my date creation is wrong.

The "date_field" is type DATE

and we said...


Try:

Select *
from table
where date_field >= trunc(sysdate-1) + interval '17' hour
  and date_field < trunc(sysdate) + interval '8' hour;


I have assumed that you actually want to run the report for activity happening between 17:00 inclusive and 08:00 exclusive, in which case you should not use BETWEEN. If you want to include activities that happened exactly at 08:00:00 as well, then BETWEEN is fine. The above condition does some implicit conversions between DATE and TIMESTAMP but they are cheaper than conversions between DATE and VARCHAR2.

Your attempt has a couple of errors. You rely on implicit conversion of the TRUNC result to VARCHAR2 before concatenating it with the hour string. This makes the result dependent on NLS_DATE_FORMAT session parameter. Also, you use HH instead of HH24. The version of the query that uses VARCHAR2 as intermediate form should like this:

Select *
from table
where date_field >= to_date(to_char(sysdate-1,'YYYYMMDD')||'17:00','YYYYMMDDHH24:MI')
  and date_field <  to_date(to_char(sysdate,'YYYYMMDD')||'08:00','YYYYMMDDHH24:MI');


Note that TRUNC is not needed here as we can truncate the time portion simply by using the appropriate format.

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

THE DATE DOES NOT APPEAR AFTER RUNNING THE QUERY

ehsan, July 16, 2019 - 5:49 pm UTC

Hello Tom,

I am using the same query in "oracle sql developer" as follow:
TO_DATE(TO_CHAR(A.DATES, 'YY-MM-DD') || ' ' || A.TIMES, 'yy-mm-dd hh24:mi:ss')

but it just returns the date not the time. Both columns (A.Dates and A.Times) contain data they are not empty.
How can I fix that.

Appreciate your time and response.
Thanks

Connor McDonald
July 25, 2019 - 2:35 am UTC

This is a formatting issue. Go to Tools => Preferences => Database => NLS to nominate how you would like to see dates

More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.