How to calculate time difference in sql

oracle

I have one table named test.
In that table I have a column named test_time of type DATE. I want to calculate the time difference between test_time and sysdate in minutes.

select 1440 * (to_date('2009-07-07 22:00', 'YYYY-MM-DD hh24:mi')
- to_date('2009-07-07   19:30', 'YYYY-MM-DD hh24:mi')) diff_hours 
from dual;

this one giving time difference in minutes. But I tried this one to my table like

select 1440 * (to_date(test_time, 'YYYY-MM-DD hh24:mi')
- to_date(sysdate, 'YYYY-MM-DD hh24:mi')) diff_hours 
from test;

but I'm not able to calculate the time difference in minutes. Kindly help me to solve this problem.

Best Answer

DATEis the Oracle datetime data type for storing a datetime value with a precision of one second. The function TO_DATE converts a character type (VARCHAR2,CHAR,...) to the DATE type. The first string is the string to convert, the secons string tell the convert function which format is used to code the date in the first string. So the result of TO_DATE('2014-04-18 10:33', 'YYYY-MM-DD HH24:MI') is the DATE equivalent to '2014-04-18 10:33:00'. The seconds are set to 0.

The function SYSDATE returns a DATE value so it must not be converted further. The column test_time is of data type DATE, too, it also must not be converted further. To get the DATEdifference you have only to calculate test_time-SYSDATE This difference of two DATE values gives the number of days. Therefore you have to multiply the above value by 1440 (=24*60, the number of minutes per day). You end up with

select (test_time - sysdate)*24*60
  from test;

This value is negative if test_time is lies in the past. If you want an integer value then round the result

select round((test_time - sysdate)*24*60,0)
  from test;