Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1rdXBB-0065K7-CV for pgsql-general@arkaria.postgresql.org; Fri, 23 Feb 2024 15:09:37 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1rdXB9-001iPK-RV for pgsql-general@arkaria.postgresql.org; Fri, 23 Feb 2024 15:09:36 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1rdXB9-001iPC-H6 for pgsql-general@lists.postgresql.org; Fri, 23 Feb 2024 15:09:36 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1rdXB3-000XKP-2x for pgsql-general@lists.postgresql.org; Fri, 23 Feb 2024 15:09:35 +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 41NF9PYD813881; Fri, 23 Feb 2024 10:09:25 -0500 From: Tom Lane To: =?UTF-8?B?6rmA66qF7KSA?= cc: pgsql-general@lists.postgresql.org Subject: Re: Fwd: Unexpected Multiple Records from Randomized Query In-reply-to: References: Comments: In-reply-to =?UTF-8?B?6rmA66qF7KSA?= message dated "Fri, 23 Feb 2024 00:58:51 +0900" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <813879.1708700965.1@sss.pgh.pa.us> Date: Fri, 23 Feb 2024 10:09:25 -0500 Message-ID: <813880.1708700965@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk =?UTF-8?B?6rmA66qF7KSA?= writes: > explain analyze > SELECT * FROM users WHERE name = 'User '||trunc(random()*100) ; > I expected the result to return one record. However, in some cases, the > result comes back with 2 or 3 records. What am I doing wrong? random() is re-evaluated at each row, so it's not that surprising if you sometimes get multiple matches. This is the same behavior that you relied on to fill the table with not-all-the-same names. The preferred way to avoid that is to stuff the random() call into a CTE: WITH x AS (SELECT random() AS r) SELECT * FROM users, x WHERE name = 'User '||trunc(r*100) ; or in this case better to shove the whole constant computation into the CTE. regards, tom lane