Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Add Interval to Timestamp from column value

I need to add minutes coming from an integer column with a timestamp to compare to another column.

Here's an example:

 SELECT t1.id_liame, t1.id_table, t1.periodicidade , t3.data_extracao, 
    CASE WHEN(NOW() < (e.data_extracao + INTERVAL t1.periodicidade || '
    MINUTES')) 
    THEN 'yes' ELSE 'no' END
    FROM table1 as t1 LEFT JOIN liame_has_extracao as t2 USING(id_liame)
    LEFT JOIN extracao as t3 USING(id_extracao)

l.periodicidade is integer (minutes)
I need to verify if data_extracao(timestamp) is greater then NOW() + l.periodicidade(integer - minutes).

How can i do it?

like image 255
NakaBr Avatar asked Jul 02 '12 13:07

NakaBr


People also ask

How do I create an interval in PostgreSQL?

In PostgreSQL, the make_interval() function creates an interval from years, months, weeks, days, hours, minutes and seconds fields. You provide the years, months, weeks, days, hours, minutes and/or seconds fields, and it will return an interval in the interval data type.

Does Dateadd work in PostgreSQL?

Although PostgreSQL does not provide DATEADD function similar to SQL Server, Sybase or MySQL, you can use datetime arithmetic with interval literals to get the same results.

What is now () in PostgreSQL?

The PostgreSQL now function returns the current date and time with the time zone.


1 Answers

You can write your query like this:

SELECT 
   t1.id_liame,
   t1.id_table,
   t1.periodicidade,
   t3.data_extracao,
   CASE
      WHEN(NOW() < (t3.data_extracao + (INTERVAL '1 min' * t1.periodicidade))) 
      THEN 'yes' ELSE 'no'
   END
FROM table1 AS t1
LEFT JOIN liame_has_extracao AS t2 USING(id_liame)
LEFT JOIN extracao AS t3 USING(id_extracao)

As you can see, you can multiply intervals with integers so with INTERVAL '1 minute' you define your base unit and multiply your actual time interval.

Hope that helps

like image 58
Frank Bollack Avatar answered Oct 22 '22 17:10

Frank Bollack