pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: David Johnston <polobo@yahoo.com>
To: 'JORGE MALDONADO' <jorgemal1960@gmail.com>
To: pgsql-sql@postgresql.org
Subject: Re: Query with LIMIT clause
Date: Sun, 9 Sep 2012 13:45:25 -0400
Message-ID: <019f01cd8eb2$e4f4be20$aede3a60$@yahoo.com> (raw)
In-Reply-To: <CAAY=A7-v4-iSVgrapiFjq4wujyVqyW-7s0vsJHu7dLb93g__eA@mail.gmail.com>
References: <CAAY=A7-v4-iSVgrapiFjq4wujyVqyW-7s0vsJHu7dLb93g__eA@mail.gmail.com>

From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-owner@postgresql.org]
On Behalf Of JORGE MALDONADO
Sent: Sunday, September 09, 2012 1:26 PM
To: pgsql-sql@postgresql.org
Subject: [SQL] Query with LIMIT clause

I have the following records that I get from a query, the fields are date
type in day/month/year format:

------------------------------------- 
Initial           Final
Date            Date
-------------------------------------
27/08/2012   04/09/2012
29/08/2012   09/09/2012
28/08/2012   09/09/2012
30/08/2012   09/09/2012
30/08/2012   09/09/2012
27/08/2012   09/09/2012
31/08/2012   09/09/2012
28/08/2012   10/09/2012
05/09/2012   16/09/2012

As you can see, this result is ordered by Final Date. What I need is to get
the last 5 records only. If I use the LIMIT 5 clause I get the first 5. I
have tried an ORDEY BY DESC but the result is the same. I will very much
appreciate your comments.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.

First, you should really order by both columns, not just "final date".  The
ties on 9/9/12 are unordered.

Second, you will indeed need to reverse the sort order and then take the
first 5 records; figuring out and limiting on the last 5 isn't worth the
effort.

SELECT initial_date, final_date
FROM date_source
ORDER BY final_date DESC, initial_date DESC
LIMIT 5

You can put the above into a sub-query and re-order if the final result is
needed in ascending order.

If this doesn't seem to work you will want to provide the exact
query/queries you are trying so that someone may spot what you are doing
wrong.

Dave






view thread (4+ messages)  latest in thread

Message-ID: <019f01cd8eb2$e4f4be20$aede3a60$@yahoo.com>
Permalink:  ../019f01cd8eb2$e4f4be20$aede3a60$@yahoo.com/
Also on:    postgresql.org/message-id/019f01cd8eb2$e4f4be20$aede3a60$@yahoo.com

 · 

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: polobo@yahoo.com, jorgemal1960@gmail.com
  Subject: Re: Query with LIMIT clause
  In-Reply-To: <019f01cd8eb2$e4f4be20$aede3a60$@yahoo.com>

* 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