Re: [SQL] Query based on date/time field

From: Herouth Maoz <herouth(at)oumail(dot)openu(dot)ac(dot)il>
To: pgsql-sql(at)postgreSQL(dot)org
Subject: Re: [SQL] Query based on date/time field
Date: 1998-08-12 12:25:39
Message-ID: l03110703b1f737b60584@[147.233.159.109]
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers pgsql-sql

At 15:50 +0300 on 12/8/98, Holger Mitterwald wrote:

> On Tue, 4 Aug 1998, William McCracken wrote:
>
> > I am new to SQL and was wondering how I would go
> > about selecting records from my database based on
> > the age of a date/time stamp.
> >
> > For example if I wanted to select records older than
> > 12 hours or 1 day.
> >
> > Any help would be appreciated.
>
> Sorry for my late response, but I was on holiday.
> I use some statement like this to select entries that are not older than 2
> weeks:
>
> SELECT DISTINCT landkreis FROM kneipe WHERE 1209600 >= (date_part('epoch',
> current_date) - date_part('epoch',datum));
>
> datum is of type datetime.
>
> what I do is the following: epoch returns the seconds since january 1st
> 1970 (I think). I substract the timestamp of each record from the current
> timestamp (current_date). The result has to be smaller than the duration
> for 2 weeks (in seconds, which is 1209600s).
>
> I dont know if there is a better solution, but it works fine.

I think the following is simpler and more intuitive:

SELECT * FROM the_table
WHERE the_date >= ('now'::datetime - '12 hours'::timespan);

This assumes that the field "the_date" in "the_table" is of type datetime.
If it isn't, just convert it by using datetime( the_date ).

The amount of time described by the type timespan is very intuitive - it
accepts, as you see, things like '12 hours', '1 day', or '2 months'. It
takes months correctly - with longer and shorter months taken into
accounts. More about it in the pgbuiltin manpage.

Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Aleksey Dashevsky 1998-08-12 12:47:45 Re: [SQL] Query based on date/time field
Previous Message Jan Wieck 1998-08-12 11:51:09 Re: AW: [HACKERS] Rule system

Browse pgsql-sql by date

  From Date Subject
Next Message Aleksey Dashevsky 1998-08-12 12:47:45 Re: [SQL] Query based on date/time field
Previous Message Marc Howard Zuckman 1998-08-12 11:33:19 Re: [SQL] Subquery problems