type casting a subselect as an interval

Started by Jean-Christian Imbeaultabout 23 years ago4 messagesgeneral
Jump to latest
#1Jean-Christian Imbeault
jc@mega-bucks.co.jp

How can I cast the return value of a sub-select as an interval?

Something like:

select current_timestamp - interval '(select days from T) days'

Thanks!

Jc

#2Karel Zak
zakkr@zf.jcu.cz
In reply to: Jean-Christian Imbeault (#1)
Re: type casting a subselect as an interval

On Fri, Feb 21, 2003 at 07:59:19PM +0900, Jean-Christian Imbeault wrote:

How can I cast the return value of a sub-select as an interval?

Something like:

select current_timestamp - interval '(select days from T) days'

You can cast it in the subselect:

select current_timestamp - (select (days::text || 'd')::interval from T);

Karel
--
Karel Zak <zakkr@zf.jcu.cz>
http://home.zf.jcu.cz/~zakkr/

#3Tom Lane
tgl@sss.pgh.pa.us
In reply to: Karel Zak (#2)
Re: type casting a subselect as an interval

Karel Zak <zakkr@zf.jcu.cz> writes:

On Fri, Feb 21, 2003 at 07:59:19PM +0900, Jean-Christian Imbeault wrote:

How can I cast the return value of a sub-select as an interval?
select current_timestamp - interval '(select days from T) days'

You can cast it in the subselect:

select current_timestamp - (select (days::text || 'd')::interval from T);

A better way of converting numeric values to intervals is to rely on the
interval-times-float8 operator:

select current_timestamp - (select days from T) * interval '1 day';

This is readable, efficient, and easily adapted to other units (second,
month, etc).

regards, tom lane

#4Stephan Szabo
sszabo@megazone23.bigpanda.com
In reply to: Tom Lane (#3)
Re: type casting a subselect as an interval

On Fri, 21 Feb 2003, Tom Lane wrote:

Karel Zak <zakkr@zf.jcu.cz> writes:

On Fri, Feb 21, 2003 at 07:59:19PM +0900, Jean-Christian Imbeault wrote:

How can I cast the return value of a sub-select as an interval?
select current_timestamp - interval '(select days from T) days'

You can cast it in the subselect:

select current_timestamp - (select (days::text || 'd')::interval from T);

A better way of converting numeric values to intervals is to rely on the
interval-times-float8 operator:

select current_timestamp - (select days from T) * interval '1 day';

This is readable, efficient, and easily adapted to other units (second,
month, etc)

Since this comes up so often would it make sense to add it to the FAQ
(possibly along with a short description of what interval 'blah' means
since people seem to keep wanting to use it as a cast)