I'm working with PostgreSQL 9.4 and I discovered today the Daterange
type. Until now I used a field startDateTime and an other field startEndTime, so what would be the benefits of using the Daterange
type instead?
The date format for the date data type in PostgreSQL is yyyy-mm-dd . This is the format used for both storing data and for inserting data.
Use the PostgreSQL AGE() function to retrieve the interval between two timestamps or dates. This function takes two arguments: the first is the end date and the second is the start date.
This can be done in PostgreSQL using the AGE() function. This function takes in two timestamps as arguments and then returns the interval between them.
clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command. timeofday() is a historical PostgreSQL function.
There is nothing that you can't do with a startDateTime
and an endDateTime
that you can do with a tsrange
(or daterange
for date
s). However, there a quite a few operators on range types that make writing queries far more concise and understandable. Operators like overlap &&
, containment @>
and adjacency -|-
between two ranges are especially useful for date and time ranges. A big bonus for range types is that you apply a gist
index on them which makes searches much faster.
As an example, find all rows where an event
takes place within a certain time range:
Start/end
SELECT *
FROM events
WHERE startDateTime >= '2016-01-01'::timestamp
AND endDateTime < '2016-01-19'::timestamp;
Range
SELECT *
FROM events
WHERE startEndRange <@ tsrange('2016-01-01'::timestamp, '2016-01-19'::timestamp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With