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 1lzJmE-0007A4-AH for pgsql-sql@arkaria.postgresql.org; Fri, 02 Jul 2021 14:04:18 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1lzJmC-0003nQ-5Y for pgsql-sql@arkaria.postgresql.org; Fri, 02 Jul 2021 14:04:16 +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 1lzJmB-0003nI-Tg for pgsql-sql@lists.postgresql.org; Fri, 02 Jul 2021 14:04:15 +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 1lzJm9-0007Xa-Mn for pgsql-sql@lists.postgresql.org; Fri, 02 Jul 2021 14:04:14 +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 162E4Aea807952; Fri, 2 Jul 2021 10:04:10 -0400 From: Tom Lane To: =?UTF-8?B?0JTQvNC40YLRgNC40Lkg0JjQstCw0L3QvtCy?= cc: pgsql-sql Subject: Re: LAST_VALUE returns the entire partition In-reply-to: References: Comments: In-reply-to =?UTF-8?B?0JTQvNC40YLRgNC40Lkg0JjQstCw0L3QvtCy?= message dated "Fri, 02 Jul 2021 17:04:47 +0500" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <807950.1625234650.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Fri, 02 Jul 2021 10:04:10 -0400 Message-ID: <807951.1625234650@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk =3D?UTF-8?B?0JTQvNC40YLRgNC40Lkg0JjQstCw0L3QvtCy?=3D writes: > I cannot understand the behavior of the last_value function. Conditions > opposite to first_value conditions. Why such a result? The default window frame isn't symmetrical is why. Per the manual [1]: Note that first_value, last_value, and nth_value consider only the rows within the =E2=80=9Cwindow frame=E2=80=9D, which by default conta= ins the rows from the start of the partition through the last peer of the current row. This is likely to give unhelpful results for last_value and sometimes also nth_value. You can redefine the frame by adding a suitable frame specification (RANGE, ROWS or GROUPS) to the OVER clause. See Section 4.2.8 for more information about frame specifications. That is, if you do nothing to change it then first_value returns the value at the first row of the partition, while last_value returns the value at the last peer of the current row (which isn't even very well-defined when the current row has some peers). regards, tom lane [1] https://www.postgresql.org/docs/current/functions-window.html