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 1ngPct-00049e-6B for pgsql-general@arkaria.postgresql.org; Mon, 18 Apr 2022 11:33:03 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1ngPcr-0004ZY-PY for pgsql-general@arkaria.postgresql.org; Mon, 18 Apr 2022 11:33:01 +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 1ngPcr-0004ZP-94 for pgsql-general@lists.postgresql.org; Mon, 18 Apr 2022 11:33:01 +0000 Received: from mail-ej1-x635.google.com ([2a00:1450:4864:20::635]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1ngPck-0003se-DS for pgsql-general@lists.postgresql.org; Mon, 18 Apr 2022 11:33:00 +0000 Received: by mail-ej1-x635.google.com with SMTP id i27so26325304ejd.9 for ; Mon, 18 Apr 2022 04:32:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=mime-version:subject:from:in-reply-to:date:cc :content-transfer-encoding:message-id:references:to; bh=o3h53CR7zvBAqGKG9knEIg2SeAnWqJgPkGFNxwgohBQ=; b=Yb+5eKiib5N2Vh+tuAHkZH1jJ+AL0haWIemCPPOw+TanbMK7Xm1AzTGMaJfE6YojKF V4dazHhvj0tfCakGCH4Ki2QXeOwAvGvkq0Dk4k4iYhkRpkbtzoZA/Nt3vUrMtYMH4U+4 GBOSbaYLc9c/EtYa4h7SR+Brx6iv3OLxhUaKaZDIgDWl7ZS/JgBr4pD78zBSjKr29PZy lt3WuhBjJFQItOsXX/r2lb1VJycbXELkO5URRTh7Nhsjmjbu8Jp8V9x7CAKKgD1Oq/Uf zBT6bxk71Jy14h6lsYwqRpbagKpMko6DBANBfkZTxNpNpb6X9Ydq/bE6ejy+dh1VNhnU HDuA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:mime-version:subject:from:in-reply-to:date:cc :content-transfer-encoding:message-id:references:to; bh=o3h53CR7zvBAqGKG9knEIg2SeAnWqJgPkGFNxwgohBQ=; b=OliBoMTyWdnV2N9ERM2XvRmHAzYJ+CRcMCm0W+KBiQeu2JUYRL5a8qNHU0n5bjqVFR CP/9Ij8KQMaNMhkUqy/zqWrN3pTJCOTTwii24yKFx6+D6E11yi6pWGwLHhElI/xL1Zo2 r+Wksi6l3qp3jaqOFwj2FSeKawbA2aIeEgrTNhoae4g0miwpuJR0xqFLvNyJwu+1XxP9 MMTXZXMlaXIn3EqJ1Cr7Xhdo/albFtM9eoW7oXl3nbcPxJl9/f/JotFXvQswQftpFBhS GXflM8SgJC9vVLWNVaGxVI5uBFRHm/j78gUNzA1Yf65rJdwutqjz8/lp4dhO7wGne0uY PQmg== X-Gm-Message-State: AOAM532iFljaNOF1In0mAmNzmAdRKXY7SbECbpIKE4uQmtQ1Ber0BkfR x2cj4f7wKD5dbTpcgRstoGM= X-Google-Smtp-Source: ABdhPJygu2c8+uN9LHANkKvuDqBQBLMVXnyvVN9iLuyhH9hlHV1mJIyQepFpoOX83jDDrb9S4vENJg== X-Received: by 2002:a17:907:6e89:b0:6e8:d79a:dced with SMTP id sh9-20020a1709076e8900b006e8d79adcedmr8707899ejc.563.1650281571825; Mon, 18 Apr 2022 04:32:51 -0700 (PDT) Received: from hollewijn.internal (217-19-30-105.dsl.cambrium.nl. [217.19.30.105]) by smtp.gmail.com with ESMTPSA id h30-20020a056402095e00b00422eedf16b4sm4615779edz.60.2022.04.18.04.32.51 (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Mon, 18 Apr 2022 04:32:51 -0700 (PDT) Content-Type: text/plain; charset=utf-8 Mime-Version: 1.0 (Mac OS X Mail 13.4 \(3608.120.23.2.7\)) Subject: Re: Puzzline CROSS JOIN when doing RECURSIVE CTE From: Alban Hertroys In-Reply-To: Date: Mon, 18 Apr 2022 13:32:50 +0200 Cc: PostgreSQL General Content-Transfer-Encoding: quoted-printable Message-Id: <75A77395-B71B-438C-A48B-9731A19DDCDF@gmail.com> References: To: =?utf-8?B?UMOzbCBVYSBMYW/DrW5lY2jDoWlu?= X-Mailer: Apple Mail (2.3608.120.23.2.7) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk > On 18 Apr 2022, at 11:56, P=C3=B3l Ua Lao=C3=ADnech=C3=A1in = wrote: (=E2=80=A6) > All of the code below is available on the fiddle here: >=20 > = https://dbfiddle.uk/?rdbms=3Dpostgres_13&fiddle=3D0cc20c9081867131260e6e35= 50bd08ab (=E2=80=A6) > OK, grand, now I wish to perform a RECURSIVE CTE on it. So, I start by > trying something (I thought was) very simple. Obviously, I plan to do > more, but I wanted to get the "mechanics" correct to start with. So, > my query is: >=20 > WITH RECURSIVE cte1 (n, ln) AS > ( > SELECT 1 AS n, string > FROM line Here is your first problem, this will yield a result for each row in = your line table, numbering it =E2=80=981=E2=80=99. You seem to have = expected just a single result here, but that is something that you need = to take care of in your query. This part is called the base case, base step or initial step. > UNION ALL > SELECT n + 1, ln > FROM cte1 > WHERE n < (SELECT COUNT(*) FROM line) And then for each of those rows, it will add all those rows (from the = same CTE!) again. This part is called the recursive step. You did add a termination condition here, which indeed manages to = terminate, but it does so too late. It seems that you do understand some of the concepts of recursive = CTE=E2=80=99s, but you appear to be missing some crucial knowledge. For example, it is actually possible to query multiple trees with a = single recursive CTE. It is not limited to a single tree. How many trees = the CTE will navigate depends on how you selected the rows in the base = case. > ) > SELECT * FROM cte1; >=20 > i.e. have a counter variable and a string from the line table My first question is why you=E2=80=99re using a recursive CTE here? This = doesn=E2=80=99t appear to be hierarchical data (such as a tree), unless = perhaps you intended to actually traverse the HTML document hierarchy? >=20 > But, then to my horror, the result of this query is >=20 > 1with t(x) as (values( XMLPARSE(DOCUMENT > (' AlarmCode=3D"mail" AlarmStartTime=3D"10:00:00" AlarmTime=3D"0" Id =3D"2"= >> Id=3D"2"><![CDATA[aaaaaaaaaaaaa]]> 1 > 1 > 1 > 1 more stuff > 1 more stuff > 1 > 1 > 1 > ... > ... snipped for brevity > ... >=20 > 256 rows! <<=3D=3D=3D note 256! >=20 >=20 > So, my simple recursive CTE is >=20 > a) not incrementing n and It should be, but only after the first 16 rows from your base case. > b) obviously doing some sort of CROSS JOIN (16^2 =3D 256). Not quite, it=E2=80=99s selecting the same 16 rows 16 times, = incrementing the numbering each time. Effectively it is indeed a = Cartesian product. More on that below. > I would be grateful if somebody could explain what's going on here. As > shown in the fiddle, I can do the basic 1 - 10 RCTE and I've done way > more complex ones before, so I'm a bit baffled as to what's going on > here. For a recursive CTE to work, you need two things, and that seems to be = where you have misunderstood some things: 1. You need a base case that selects the _initial_ rows to start the = recursion from. 2. You need a recursive step, where you usually join the results of your = CTE to your table to figure out what the next result should be. (It is very similar to how this works in procedural languages, where you = first call a function that initiates the recursion and then that calls a = second function (with more parameters usually) that calls itself again = and again, with updated input parameters, until some termination = condition is reached and the function returns a value.) For the base case, you will want to make sure that you select the = correct row(s) from your line table for the initial set. My guess is = that it should be the row containing the string ''. For the recursive step, you will want to select the next child row from = your line table that is (directly) related to the one(s) you selected in = the base case, or is (directly) related to the previous iteration of the = recursive case. It is unclear to me what that should be in your case, I don=E2=80=99t = understand the purpose of your CTE. Your termination condition, WHERE n < (SELECT COUNT(*) FROM line), = isn=E2=80=99t quite doing what you expect either I think. Let=E2=80=99s say that c =3D (SELECT COUNT(*) FROM line), so c =3D 16 in = your example. - The first iteration of the CTE, the base case, will select 16 lines = with n=3D1. - The second iteration is the first time in the recursive step, and will = select all lines from the base case where n < c, or 1 < 16, which is all = of them. - The next iteration will select all rows where 2 < 16, then 3 < 16, =E2=80= =A6 until finally in the 16th iteration it stops with the test 16 < 16. So, you managed to make the recursion terminate at least, but probably = not how you intended it to work. Something along the lines of: WITH RECURSIVE cte (n, ln) AS ( SELECT 1, string FROM line WHERE string LIKE '%%' UNION ALL SELECT n+1, string FROM cte JOIN line ON iHaveNoClueHere ) SELECT * FROM cte; > Any explanations, references to URLs or other advice gratefully = received. There are plenty of explanations about recursive CTE=E2=80=99s in SQL on = the Internet. I would probably have a good look at how it=E2=80=99s = described in the PG documentation. There are a couple of good articles = on the topic by some PG bloggers too. You=E2=80=99ll find plenty of articles related to how to do this in = MSSQL or later Oracle versions. Those are totally fine for understanding = the principles, and even the syntax is almost entirely the same. For a PG specific explanation, this one looks pretty thorough: = https://towardsdatascience.com/recursive-sql-queries-with-postgresql-87e2a= 453f1b Regards, Alban Hertroys -- If you can't see the forest for the trees, cut the trees and you'll find there is no forest.