Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres query between yesterday at time and today at time

Tags:

postgresql

I am fairly new to postgres and I'm struggling with a query I have to write to get all records between yesterday at 18:00 and today at 18:00.

So far I've tried a predicate like this but it doesn't seem to be right because whilst the query runs I don't get the desired result...

WHERE 
   recon_vr.paymentDateTime >= CURRENT_DATE -1 + '18:00:00.000000'::time
AND    
   recon_vr.paymentDateTime >= CURRENT_DATE + '18:00:00.000000'::time

Could someone please help me with this?

Also, I am running the query from an integration tool which I have found sometimes has issues with the :: syntax. So any solutions without that would be greatly appreciated. But if none exists then that's fine too.

thanks in advance

like image 794
Richie Avatar asked Jul 12 '17 07:07

Richie


People also ask

How do I get PostgreSQL yesterday?

Use current_date to get today's date. Note that you don't need brackets at the end of the current_date function. In PostgreSQL, you can subtract or add any number of days using the INTEGER keyword. Here, since you need to subtract one day, you use - INTEGER '1' to get yesterday's date.

What is interval in PostgreSQL?

In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years. It also has additional attribute called “precision (denoted by p)” that can be used to set the level of precision in the query results.


1 Answers

Your query is right in general, but has a mistake, wrong operator – you used 2 >= instead of >= and <=.

So the correct one is:

WHERE 
   recon_vr.paymentDateTime >= CURRENT_DATE - 1 + '18:00:00.000000'::time
AND    
   recon_vr.paymentDateTime <= CURRENT_DATE + '18:00:00.000000'::time

Also, you could use BETWEEN:

WHERE 
   recon_vr.paymentDateTime BETWEEN CURRENT_DATE - 1 + '18:00:00.000000'::time AND CURRENT_DATE + '18:00:00.000000'::time

To avoid issues with ::time you can write it like this:

WHERE 
   recon_vr.paymentDateTime BETWEEN CURRENT_DATE - 1 + TIME '18:00' AND CURRENT_DATE + TIME '18:00'

...or like this:

WHERE 
   recon_vr.paymentDateTime BETWEEN CURRENT_DATE - 1 + INTERVAL '18h' AND CURRENT_DATE + INTERVAL '18h'

BTW, using CamelStyle object names in Postgres can lead to some unpleasant issues – by default, all names are case-insensitive (so you can easily write recon_vr.paymentDateTime in your case), unless you've used double-quoting at creation time. If so, you'll need to use double quoting forever (recon_vr."paymentDateTime" gives you pure camel-styled colunm name, but you'll need to use double quotes to work with it, not that convenient).

like image 103
Nick Avatar answered Nov 15 '22 07:11

Nick