Re: Subquery to select max(date) value

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Rich Shepard <rshepard(at)appl-ecosys(dot)com>
Cc: "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Subquery to select max(date) value
Date: 2019-03-28 23:05:59
Message-ID: CAKFQuwbQ6f9Kqqs-H+js9hi-9c1Q4pWT9pj=Kq9h3Ld2yVCCoA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Mar 28, 2019 at 3:59 PM Rich Shepard <rshepard(at)appl-ecosys(dot)com>
wrote:

> select p.person_id, p.lname, p.fname, p.direct_phone, p.active,
> o.org_name, sq.*
> from people as p
> join organizations as o on p.org_id = o.org_id
> cross join
> lateral
> (select a.next_contact
> from activities as a
> where a.person_id = p.person_id and
> p.active='True' and
> a.next_contact is not null
> order by a.next_contact DESC
> limit 1) sq;
>
> It works wellm, but the row order is not that of a.next_contact. In fact,
> there seems to be no order in the returned set.

The next_contact column is
> in the lateral sub-query. Does this make a difference?
>

Yes, if you join the result on an ordered subquery to anything you no
longer have a guaranteed order for the combined relation.

select ...
from ...
join ...
cross join lateral ...
-- now add an order by for the top-level query
order by

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2019-03-28 23:07:09 Re: Subquery to select max(date) value
Previous Message Ken Tanzer 2019-03-28 23:05:04 Re: Subquery to select max(date) value