20

When I call max on two timestamps, I get an error :

select max(now()::timestamp, to_timestamp('2021-01-01', 'YYYY-MM-DD')::timestamp);
-- ERROR:  function max(timestamp without time zone, timestamp without time zone) does not exist

My actual usage would be in an upsert query, where I would like to write :

INSERT ...
ON CONFLICT (pk) DO UPDATE SET
  ts = max(table.ts, excluded.ts)

Question

Is there an idiomatic way to take the max between two timestamps in PostgreSQL ?

2 Answers 2

35

I guess you are looking for the greatest() function.

demo:db<>fiddle

max() (link to docs) is an aggregate function which returns the greatest value of a group of records.
greatest() (link to docs) takes the greatest value of an arbitrary number of parameters - two in your case. It can be used for type timestamp as well.


extra note : the function to take the smallest value of an arbitrary number of parameters is named least() (same link) (not "smallest")

0
4

Use GREATEST:

SELECT GREATEST(now()::timestamp, to_timestamp('2021-01-01', 'YYYY-MM-DD')::timestamp);

The GREATEST scalar function takes one or more arguments and returns the largest value of those inputs.

Not the answer you're looking for? Browse other questions tagged or ask your own question.