简体   繁体   中英

How to determine if one timestamp precedes another in postgresql?

I want to add constraints to a table, requiring checkout_time to proceed return_time and both of these to be before now, if present.

What is the right way to do this in PostgreSQL? I was unable to determine which date functions were most appropriate.

You can simply compare times with each other like any other value.

postgres=# SELECT TIMESTAMP '2011-03-11 10:40:13' < NOW();
 ?column? 
----------
 t
(1 row)

So you can compare values very easily. So with your table, you can add a CHECK constraint.

CREATE TABLE foo(
    mydateTIMESTAMP
    CHECK (mydate < NOW()));

You can make as many CHECK s for the table as you need and add combine them with logical operators

In addition to DrColossos answer, here is the check for the "one before the other":

ALTER TABLE foo 
   ADD CONSTRAINT check_time CHECK (checkout_time < return_time)

Why don't you just use the < operator?

mydb=# select '2011-03-01'::timestamp < '2011-03-02'::timestamp;
 ?column? 
----------
 t
(1 row)

mydb=# select '2011-03-01'::timestamp < '2011-03-01'::timestamp;
 ?column? 
----------
 f
(1 row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM