Calculate time difference in minutes

redshifttime

I am Amazon Redshift. I tried to calculate the time difference between two time stamp columns in minutes, but the timestampdiff function does not work on it. The error is telling me that minute column does not exist in the table I query. At the same time some answers suggest that timestampdiff does not work for PostgreSQL, but function like date_part does not work on my end as well. Could anyone share experience or any document for the grammar and function on Amazon Redshift?

  select 
      email,
      createddate,
      lastloggedin,
      timestampdiff(minute, createddate, lastloggedin)
       from udb.user
       where createddate >= '2019-09-01' and createddate <= '2019-09-30'
Error: [Amazon](500310) Invalid operation: column "minute" does not exist in user; 
[SQL State=42703, DB Errorcode=500310]
1 statement failed.

Best Answer

Checking the docs for Amazon Redshift shows this:

DATEDIFF ( datepart, {date|time|timetz|timestamp}, {date|time|time|timestamp} )

datepart: The specific part of the date or time value (year, month, or day, hour, minute, second, millisecond, or microsecond) that the function operates on. For more information, see Date parts for date or timestamp functions.

  • Specifically, DATEDIFF determines the number of date part boundaries that are crossed between two expressions. For example, suppose that you're calculating the difference in years between two dates, 12-31-2008 and 01-01-2009. In this case, the function returns 1 year despite the fact that these dates are only one day apart. If you are finding the difference in hours between two timestamps, 01-01-2009 8:30:00 and 01-01-2009 10:00:00, the result is 2 hours. If you are finding the difference in hours between two timestamps, 8:30:00 and 10:00:00, the result is 2 hours.

date|time|timetz|timestamp: A DATE, TIME, TIMETZ, or TIMESTAMP column or expressions that implicitly convert to a DATE, TIME, TIMETZ, or TIMESTAMP. The expressions must both contain the specified date or time part. If the second date or time is later than the first date or time, the result is positive. If the second date or time is earlier than the first date or time, the result is negative.

So, your query should be:

select 
    email,
    createddate,
    lastloggedin,
    datediff(minute, createddate, lastloggedin)
from udb.user
where createddate >= '2019-09-01' and createddate <= '2019-09-30'