Re: Extract only maximum date from column

From: Alban Hertroys <haramrae(at)gmail(dot)com>
To: Rich Shepard <rshepard(at)appl-ecosys(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Extract only maximum date from column
Date: 2025-12-04 22:58:17
Message-ID: BE035292-C9E3-4A46-9DD1-7026A16292DF@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-general


> On 4 Dec 2025, at 20:55, Rich Shepard <rshepard(at)appl-ecosys(dot)com> wrote:
>
> I want the script to extract only the maximum `next_contact' date and
> haven't learned how to do this from my reading of web sites.
>
> The script:
>
> select p.person_nbr, p.company_nbr, c.next_contact
> from people as p, contacts as c
> where c.next_contact >= '2025-11-01'
> group by p.person_nbr, p.company_nbr, c.next_contact
> order by p.person_nbr, p.company_nbr, max(c.next_contact);
>
> returns all contacts rather than only the latest one.
>
> Is using a sub-select the proper way?
>
> TIA,
>
> Rich

That looks like a classical case for a correlated subquery with WHERE NOT EXISTS.

Something like:

select p.person_nbr, p.company_nbr, c.next_contact
from people as p
join contacts as c
on -- I’m really missing some kind of relation between p and c here, I think that’s relevant
where c.next_contact >= ‘2025-11-01’
-- make sure there’s no later contact
and not exists (
select 1 -- the value is irrelevant, as long as there’s no later instance of a contact
from contacts c2
where c2.next_contact >= ‘2025-11-01’
and c2.next_contact > c.next_contact
)

P.S. My mail-client tried to outsmart me in this reply (in no small part) and I just got back from the pub, so I can’t exactly guarantee correctness of the above, but the principal idea should be solid.

Alban Hertroys
--
There is always an exception to always.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Bernice Southey 2025-12-05 09:35:50 Re: Extract only maximum date from column
Previous Message Adrian Klaver 2025-12-04 22:33:23 Re: Extract only maximum date from column