Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL get items from last 12 hours

Tags:

php

postgresql

I have the following query to get what I want in PHP file, it does it's job except the WHERE part. I need to get items that have date_time1 column for last 12 hours.

SELECT p.*, t.*  FROM posts AS p  LEFT JOIN posted_tweets AS t  ON p.a_id = t.p_id WHERE p.date_time1 >= now() AND t.date_time = (      SELECT MAX(date_time)      FROM posted_tweets AS t2      WHERE t2.p_id = t.p_id )     OR t.date_time IS NULL  

How exactly should I edit p.date_time1 >= now() part to reach my aim? Thanks.

like image 471
malisit Avatar asked Sep 01 '15 04:09

malisit


People also ask

How do I get last 24 hours record in PostgreSQL?

Use NOW() to get a timestamptz. This ensures you will get the last 24 hours no matter what your time zone or daylight savings says.

How do I get last 24 hours records in SQL Server?

If you want to select the last 24 hours from a datetime field, substitute 'curate()' with 'now()'. This also includes the time.

How do I get last one hour data in SQL?

Here is the SQL to show latest time using now() function. Here is the SQL to get last 1 hour data in MySQL. In the above query, we select only those rows whose order_date falls within past 1 hour interval. We use INTERVAL clause to easily substract 1 hour interval from present time obtained using now() function.


2 Answers

The following should restrict to all times occurring in the last 12 hours:

w.date_time1 >= (NOW() - INTERVAL '12 hours' ) 

Check here for a good discussion of handling datetime in Postgresql, along with examples.

like image 57
Tim Biegeleisen Avatar answered Sep 23 '22 13:09

Tim Biegeleisen


Replace now() with an appropriate time function from here.

EDIT: The actual issue was with the quotations; remember to use single quotes in your PostgreSQL queries.

like image 30
F. Stephen Q Avatar answered Sep 21 '22 13:09

F. Stephen Q