Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of using Postgresql Daterange type instead of two Date fields?

Tags:

postgresql

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?

like image 223
Simon Avatar asked Jan 20 '16 00:01

Simon


People also ask

What is the data type for date in PostgreSQL?

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.

How do I select data between two dates in PostgreSQL?

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.

How do I split a date and time in PostgreSQL?

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.

Which one of these will the current date and time in PostgreSQL?

clock_timestamp() returns the actual current time, and therefore its value changes even within a single SQL command. timeofday() is a historical PostgreSQL function.


1 Answers

There is nothing that you can't do with a startDateTime and an endDateTime that you can do with a tsrange (or daterange for dates). 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);
like image 108
Patrick Avatar answered Oct 10 '22 16:10

Patrick