Use now () or CURRENT_TIMESTAMP for this purpose.
The reason for the different result of your queries is the following:
When you subtract two values of type date , the result will be integer and abs() .
When you subtract two values of type timestamp (or only one of them is timestamp ), the result will be interval , and abs() not applicable. You can replace the CASE expression:
ORDER BY CASE WHEN expiry > now() THEN expiry - now() ELSE now() - expiry END
Or you can extract() unix epoch from the resulting interval , as shown in @Craig. I quote: "for interval values, the total number of seconds in the interval." Then you can use abs() again:
ORDER BY abs(extract(epoch from (expiry - now())));
age() will simply add a more humanly readable representation to the interval by adding days to months and years for larger intervals. But this concerns the point: the value is used only for sorting.
Since your column has a type timestamp, you must use CURRENT_TIMESTAMP (or now() ) instead of CURRENT_DATE , or you will get inaccurate results (or even incorrect for today).
source share