Why does postgres' upper range function for a daterange return an exclusive bound?

有些话、适合烂在心里 提交于 2019-12-10 18:06:37

问题


I've created a sql fiddle for this post: http://sqlfiddle.com/#!15/7b5d7/1/0

Question #1

Why does inserting a record with a daterange that has exclusive bounds actually store a range with an inclusive lower bound and an exclusive upper bound? Why doesn't pg store them both as inclusive bounds?

Question #2

SELECT upper('[2016-06-19, 2016-06-21)'::daterange) returns 2016-06-21. Note that [ signifies an inclusive lower bound and ) an exclusive upper bound.

Shouldn't selecting the upper bound return 2016-06-20? Don't dates have have discrete intervals?


回答1:


Re Question #1: closed-open is the standard way to handle date ranges, with 20-25 years of history in the academic literature. See pp. 24-25 of Bitemporal Data by Tom Johnston, and also Developing Time-Oriented Database Applications in SQL by Richard Snodgrass.

But I think one of the reasons is that consecutive ranges don't have overlap. If a is [May2016, Jun2016) and b is [Jun2016, Jul2016), they don't share any days. So they "snap together", and you don't have to worry about edge cases where they touch.

Note that one drawback (maybe) of closed-open is that you can't specify an empty range. [May2016, May2016) is simply a self-contradiction, whereas [May2016, May2016] is an instant.

Re Question #2: Again it could have been different, but I can think of several advantages of making upper([May2016, Jun2016)) return Jun2016:

  • It returns the same thing regardless of the resolution of the range.
  • It is more like the mathematical meaning of an open endpoint, where it is the only possible answer.
  • It returns what matches the "label", so arguably it is less surprising.
  • It lets you easily see if two ranges "meet": upper(a) = lower(b).

Also, note that in Postgres all time-related datatypes are discrete. There used to be an option to compile Postgres with float-based timestamps, but it is deprecated and I've never encountered it.



来源:https://stackoverflow.com/questions/37953786/why-does-postgres-upper-range-function-for-a-daterange-return-an-exclusive-boun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!