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 1ofSVY-0001Dn-78 for pgsql-novice@arkaria.postgresql.org; Mon, 03 Oct 2022 20:57:48 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1ofSVW-0005H6-Aw for pgsql-novice@arkaria.postgresql.org; Mon, 03 Oct 2022 20:57:46 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ofSVW-0005Gx-2i for pgsql-novice@lists.postgresql.org; Mon, 03 Oct 2022 20:57:46 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ofSVT-0005yS-Qk for pgsql-novice@lists.postgresql.org; Mon, 03 Oct 2022 20:57:45 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 293KveTq1701226; Mon, 3 Oct 2022 16:57:40 -0400 From: Tom Lane To: Onni Hakala cc: Laurenz Albe , pgsql-novice@lists.postgresql.org Subject: Re: How can I create a feature request for QUALIFY clause into PostgreSQL? In-reply-to: <02B67082-508E-4065-8AEE-0C3758021AF6@keksi.io> References: <6E722EEC-61FE-4EC0-B17D-B4468DA34BA1@keksi.io> <02B67082-508E-4065-8AEE-0C3758021AF6@keksi.io> Comments: In-reply-to Onni Hakala message dated "Mon, 03 Oct 2022 22:58:52 +0300" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1701224.1664830660.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Mon, 03 Oct 2022 16:57:40 -0400 Message-ID: <1701225.1664830660@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Onni Hakala writes: > Can you show me how you could use that to get the latest 2 events from t= he events table using DISTINCT ON? I assume you mean latest 2 events per person, else it's trivially solved with ORDER BY ... LIMIT 2. But I'd still be inclined to solve it with ORDER BY ... LIMIT: =3D> select e.* from (select distinct person from events) p cross join lateral (select e.* from events e where p.person =3D e.person order by created_at desc limit 2) e; person | event_type | created_at = --------------+-------------------+---------------------------- laurenz.albe | non-helpful reply | 2022-10-03 17:16:39.957743 someone.else | other reply | 2022-10-03 17:36:39.957743 someone.else | other reply | 2022-10-03 17:26:39.957743 onni.hakala | other reply | 2022-10-03 17:31:39.957743 onni.hakala | clarifying reply | 2022-10-03 17:21:39.957743 (5 rows) In a real application you could probably avoid the SELECT DISTINCT by joining to some other table that has just one row per person. regards, tom lane