Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.92) (envelope-from ) id 1j7nz1-0006Ax-J5 for pgsql-general@arkaria.postgresql.org; Fri, 28 Feb 2020 22:19:48 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1j7nz0-00043U-Ac for pgsql-general@arkaria.postgresql.org; Fri, 28 Feb 2020 22:19:46 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j7nyx-00043N-UY for pgsql-general@lists.postgresql.org; Fri, 28 Feb 2020 22:19:45 +0000 Received: from wout2-smtp.messagingengine.com ([64.147.123.25]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1j7nys-000868-2z for pgsql-general@postgresql.org; Fri, 28 Feb 2020 22:19:42 +0000 Received: from compute5.internal (compute5.nyi.internal [10.202.2.45]) by mailout.west.internal (Postfix) with ESMTP id 424ACE09; Fri, 28 Feb 2020 17:19:36 -0500 (EST) Received: from mailfrontend2 ([10.202.2.163]) by compute5.internal (MEProxy); Fri, 28 Feb 2020 17:19:36 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=aklaver.com; h= subject:to:cc:references:from:message-id:date:mime-version :in-reply-to:content-type:content-transfer-encoding; s=fm2; bh=e /qhas1mjvtEbj8i1XWGvwMiPgKXlr5h4Aescf9L3GY=; b=O3FeTB5BV1QfihDTl /mDCf0ZLRAc/cPTTaQhkgjLynMSfcTfs4HjPDzTYU+/GtTc6azACLVLR3wkkF5wn /LGzdN38YeVwAPloWnhJNSFAoAk14a5RTP+XZQjVR+zK0uM9hUyfhwNTgyVn2XYX 236ajh6oFf/0OC+alK6XfG7KTLBhb7LMGoQPEGv+pEghDDUlztCnWY3Cdi22Le2t vkZ5dlioL4pjRXwCFiCbXW9DT5RzJ9ZKMYa+BANOy5vDNKVwOFOtpwgH9BUQc9c7 QcVQM1tgLdTFaA2SoRdx5DrITUFhuBjurCTVbS4Y9BEDVngMEv56jnk/hxRO55Qk JI53g== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-me-proxy:x-me-proxy:x-me-sender:x-me-sender :x-sasl-enc; s=fm2; bh=e/qhas1mjvtEbj8i1XWGvwMiPgKXlr5h4Aescf9L3 GY=; b=c5sW3dK/xAb/dxr5rZpVSvZm3AylVVrSNfmAqb/FEyTyyG7557vhaz6Jb 9oqZiANUqVrYJKkxMFaf2j6to+EY1o2TWn5W4MBeQyE1R9SwlKgHFGRN03fBcklZ +xBgGGu9AuwlMbeb+2W5QE7iossi65vY38vdIGvcHpSsCHvGjw8yu8Xo5lRfUP2P 38kH2h47E5fdaHux4IapHaZo1kJNqU69dZAGWV+80urp/zsTstUZ6XlJhpSb4k1/ WRJ22uBJemVW+aymGlAcwP8gJIIYwxt1HZu/yHmaSDzp0JnsRV0wIKnfVCEDr+At ERb1uG9yU7LXzSmIQ1t0b9agISvEQ== X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgedugedrleekgdduheekucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdfqfgfvpdfurfetoffkrfgpnffqhgen uceurghilhhouhhtmecufedttdenucenucfjughrpefuvfhfhffkffgfgggjtgfgsehtje ertddtfeejnecuhfhrohhmpeetughrihgrnhcumfhlrghvvghruceorggurhhirghnrdhk lhgrvhgvrhesrghklhgrvhgvrhdrtghomheqnecukfhppeejgedrleegrdejfedrvddvvd enucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmhepmhgrihhlfhhrohhmpegrughr ihgrnhdrkhhlrghvvghrsegrkhhlrghvvghrrdgtohhm X-ME-Proxy: Received: from ranger.suse (unknown [74.94.73.222]) by mail.messagingengine.com (Postfix) with ESMTPA id DC19A3060D1A; Fri, 28 Feb 2020 17:19:34 -0500 (EST) Subject: Re: Recursive CTEs and randomness - is there something I'm missing? To: Tom Lane , =?UTF-8?B?UMOzbCBVYSBMYW/DrW5lY2jDoWlu?= Cc: pgsql-general References: <20006.1582911929@sss.pgh.pa.us> From: Adrian Klaver Message-ID: Date: Fri, 28 Feb 2020 14:19:34 -0800 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.5.0 MIME-Version: 1.0 In-Reply-To: <20006.1582911929@sss.pgh.pa.us> Content-Type: text/plain; charset=utf-8; format=flowed Content-Language: en-US Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk On 2/28/20 9:45 AM, Tom Lane wrote: > =?UTF-8?B?UMOzbCBVYSBMYW/DrW5lY2jDoWlu?= writes: >> The SQL: > >> WITH RECURSIVE rand (num, md, a_2_s) AS >> ( >> SELECT >> 1, >> MD5(RANDOM()::TEXT), >> ARRAY_TO_STRING(ARRAY(SELECT chr((65 + round(random() * 25)) :: integer) >> FROM GENERATE_SERIES(1, 5)), '') >> UNION >> SELECT num + 1, >> MD5(RANDOM()::TEXT), >> ARRAY_TO_STRING(ARRAY(SELECT chr((65 + round(random() * 25)) :: integer) >> FROM GENERATE_SERIES(1, 5)), '') >> FROM rand >> WHERE num < 5 >> ) >> SELECT * FROM rand; > >> A typical result is shown below: > >> 1 974ee059a1902e5ca1ec73c91275984b GYXYS >> 2 6cf5a974d5859eae23cdb9c310e3a3bf YFDPT >> 3 fa6be95eb720fe6f80c7c8fb6ba11171 YFDPT >> 4 fa54913b0bb43de0025b153fd71a5334 YFDPT >> 5 523fab9bdc6c4c51a89e0d901273fb69 YFDPT > >> The fact that the last 4 are identical is not a coincidence. If I put >> 100 in the GENERATE_SERIES, I still get the same result, the first and >> second records are different, but ALL subsequent instances of the >> ARRAY_TO_STRING are identical! > > Yeah, it's weird. A look at EXPLAIN VERBOSE offers some insight: > > QUERY PLAN > ------------------------------------------------------------------------------------------------------------------------ > CTE Scan on rand (cost=4.75..5.37 rows=31 width=68) > Output: rand.num, rand.md, rand.a_2_s > CTE rand > -> Recursive Union (cost=0.13..4.75 rows=31 width=68) > -> Result (cost=0.13..0.15 rows=1 width=68) > Output: 1, md5((random())::text), array_to_string($1, ''::text) > InitPlan 1 (returns $1) > -> Function Scan on pg_catalog.generate_series (cost=0.00..0.13 rows=5 width=32) > Output: chr((('65'::double precision + round((random() * '25'::double precision))))::integer) > Function Call: generate_series(1, 5) > -> WorkTable Scan on rand rand_1 (cost=0.13..0.40 rows=3 width=68) > Output: (rand_1.num + 1), md5((random())::text), array_to_string($2, ''::text) > Filter: (rand_1.num < 5) > InitPlan 2 (returns $2) > -> Function Scan on pg_catalog.generate_series generate_series_1 (cost=0.00..0.13 rows=5 width=32) > Output: chr((('65'::double precision + round((random() * '25'::double precision))))::integer) > Function Call: generate_series(1, 5) > (17 rows) > > The ARRAY sub-selects are being done as initplans, not subplans, > which means they're only done once not once per row. This is correct > so far as the planner is concerned because those sub-selects are > "uncorrelated", ie they use no values from the outer query. > > There is room to argue that because the sub-selects contain volatile > functions, they ought not be optimized into initplans. We have > traditionally not considered that, however, and I'm afraid that a > lot of people have written queries that depend on it. For example, > there's lore out there that replacing > WHERE mycol < random() > with > WHERE mycol < (SELECT random()) > will freeze the random() result as a single value rather than > computing a new value for each row, which sometimes is what you > need. These days, better practice would be to put the random() > call in a CTE, but there's still a lot of code out there that > does it as above. > > For your immediate problem, since you don't care that much > (I suppose) about exactly how the strings are generated, you > could fix the issue by making the sub-selects depend on > "num" somehow. Or possibly there's a way to do it without > a sub-select. On the whole this looks like a mighty expensive > way to generate a random string, so I'd be inclined to look > for other implementations. An off the cuff Python solution: CREATE OR REPLACE FUNCTION public.upper_random() RETURNS character varying LANGUAGE plpythonu AS $function$ from string import ascii_uppercase as au import random return ''.join(random.sample(au,5)) $function$ SELECT num, MD5(RANDOM()::TEXT), upper_random() FROM generate_series(1, 5) AS t(num); num | md5 | upper_random -----+----------------------------------+-------------- 1 | 5896a9e3efa53027873d7999e58904ae | TRGEB 2 | 9f9677c32a64b6eae73759a69e1acfff | TFQHG 3 | 5aefda5b498215065e01ba697d79caee | KYBZS 4 | 1605b7fa54fef9bdc5c49f9b79810e07 | EUDML 5 | 4ba59880c1c67bca1d1f184bda5350b6 | RFPGO > > regards, tom lane > > -- Adrian Klaver adrian.klaver@aklaver.com