1

I need to store two dates valid_from, and valid_to.

Is it better to use two datetime fields like valid_from:datetime and valid_to:datatime.

Would be it better to store data in jsonb field validity: {"from": "2001-01-01", "to": "2001-02-02"}

Much more reads than writes to database. DB: PostgresSQL 9.4

2 Answers 2

1

You can use daterange type : ie :

  • '[2001-01-01, 2001-02-02]'::daterange means from 2001-01-01 to 2001-02-02 bound inclusive
  • '(2001-01-01, 2001-02-05)'::daterange means from 2001-01-01 to 2001-02-05 bound exclusive

Also :

  • Special value like Infinite can be use
  • lower(anyrange) => lower bound of range
  • and many other things like overlap operator, see the docs ;-)

Range Type

Sign up to request clarification or add additional context in comments.

4 Comments

id | name | place | validity ----+-----------------------+--------+------------------------- ` 1 | 100% Responsive | top | [2001-01-02,2020-01-01)` ` 3 | Beautyfull Typography | top | [2001-01-02,2021-01-01)` How to find rows where date 2021-01-01 is inclusive in validity? I need row id 3 with given date 2021-01-01.
in [2001-01-02,2021-01-01) ==> 2021-01-01 is exluded
in [2001-01-02,2021-01-01] ==> 2021-01-01 is included
validity @> '2021-01-01'::date select validity range containg 2021-01-01
1

Use two timestamp columns (there is no datetime type in Postgres).

They can efficiently be indexed and they protect you from invalid timestamp values - nothing prevents you from storing "2019-02-31 28:99:00" in a JSON value.

If you very often need to use those two values to check if another tiemstamp values lies in between, you could also consider a range type that stores both values in a single column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.