Is there a max function for timestamps (with or without timezone)?
Dec 9
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 ?
1 answer
Accepted answer · original discussion
Dec 9
I guess you are looking for the greatest() function.
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 question comments
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.