pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Bryce Nesbitt <bryce1@obviously.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: extract or date_part on an interval? How many e
Date: Sun, 27 Jan 2008 22:10:40 -0500
Message-ID: <16843.1201489840@sss.pgh.pa.us> (raw)
In-Reply-To: <479D3E63.2080601@obviously.com>
References: <479D3E63.2080601@obviously.com>

Bryce Nesbitt <bryce1@obviously.com> writes:
> Hmm.  Seemed so simple.  But how do I get the number of years an
> interval represents?  extract is clearly the wrong way:

There is nothing simple about datetime calculations, ever :-(

Let me exhibit why this particular case is not as simple as you
could wish:

regression=# select '2007-02-01'::timestamp + interval '1 year';
      ?column?       
---------------------
 2008-02-01 00:00:00
(1 row)

regression=# select '2007-02-01'::timestamp + interval '365 days';
      ?column?       
---------------------
 2008-02-01 00:00:00
(1 row)

regression=# select '2008-02-01'::timestamp + interval '1 year';
      ?column?       
---------------------
 2009-02-01 00:00:00
(1 row)

regression=# select '2008-02-01'::timestamp + interval '365 days';
      ?column?       
---------------------
 2009-01-31 00:00:00
(1 row)

That is, there isn't any fixed conversion factor between N days
and N years, so the interval datatype treats them as incommensurate.

If you're willing to settle for an approximate answer, you can
do extract(epoch from interval) and then divide by however many
seconds you want to believe are in a year.  This will give various
wrong answers in various corner cases, but I'm not sure there is
a right answer.

			regards, tom lane



view thread (5+ messages)  latest in thread

Message-ID: <16843.1201489840@sss.pgh.pa.us>
Permalink:  ../16843.1201489840@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/16843.1201489840@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, bryce1@obviously.com
  Subject: Re: extract or date_part on an interval? How many e
  In-Reply-To: <16843.1201489840@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox