Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mGk8x-0006SK-Hd for pgsql-general@arkaria.postgresql.org; Thu, 19 Aug 2021 15:39:47 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mGk8u-0003sK-Mo for pgsql-general@arkaria.postgresql.org; Thu, 19 Aug 2021 15:39:44 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mGk8u-0003sC-Dd for pgsql-general@lists.postgresql.org; Thu, 19 Aug 2021 15:39:44 +0000 Received: from mail.appl-ecosys.com ([50.126.108.78]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mGk8s-0002pz-0J for pgsql-general@lists.postgresql.org; Thu, 19 Aug 2021 15:39:44 +0000 Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by mail.appl-ecosys.com (Postfix) with ESMTP id AEA502A0108 for ; Thu, 19 Aug 2021 08:39:39 -0700 (PDT) Date: Thu, 19 Aug 2021 08:39:39 -0700 (PDT) From: Rich Shepard To: pgsql-general@lists.postgresql.org Subject: Re: Selecting table row with latest date In-Reply-To: <1704154.1629384082@sss.pgh.pa.us> Message-ID: References: <1704154.1629384082@sss.pgh.pa.us> User-Agent: Alpine 2.20 (LNX 67 2015-01-07) MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII; format=flowed List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk On Thu, 19 Aug 2021, Tom Lane wrote: > The best way is usually like > select * from mytable order by contact_date desc limit 1; > If you have an index on contact_date this should work very well indeed. tom, I added an index on contact_date and the query returned only one row. Huh! Not what I expected. This is the script I need to fine-tune (and I've forgotten the role of sq since someone suggested it a few years ago): ---------- /* This query selects all whose next_contact date is today or earlier; no nulls. This version should select the most recent contact_date by person_nbr, order by person_nbr and next_contact date. STILL NEEDS WORK. */ select p.person_nbr, p.lname, p.fname, p.direct_phone, p.cell_phone, o.company_name, sq.* from people as p join companies as o on p.company_nbr = o.company_nbr cross join lateral (select * from contacts as a where a.person_nbr = p.person_nbr and a.next_contact <= current_date and a.next_contact is not null order by person_nbr, a.next_contact ASC ) sq order by sq.next_contact ASC; ---------- Rich