Skip to content
Advertisement

Cycle detected while executing recursive query

I am using CTE recursive query to get below output but don’t know why it is throwing “cycle detected while executing recursive WITH query”. Can anyone please tell me where is wrong with my query?

my query:

SELECT order_id, product_id, quantity FROM cte;

enter image description here

table/data script:

Advertisement

Answer

In the recursive member you are currently only joining on a.product_id = b.product_id, rather than a.order_id = b.order_id AND a.product_id = b.product_id; which doesn’t directly matter here but would if different orders included the same products, which is likely in the real world.

Your data and query don’t actually seem to have cycle though. You appear to be tripping over what seems to be a bug with ANSI joins; adding a cycle clause doesn’t reveal any cycling rows, as expected – and makes it work!; and it works with old-style joins:

db<>fiddle

You don’t need to join at all though; you can do:

which assigns the fixed 1 quantity in the final select, or:

which assigns it inside and needs to track the original quantity as a new alias.

For both of those I’ve removed the + 1 from the quantity comparison, as that was making it stop too early; with an order by added, they both get:

ORDER_ID PRODUCT_ID QUANTITY
ORD1 PROD1 1
ORD1 PROD1 1
ORD1 PROD1 1
ORD1 PROD1 1
ORD1 PROD1 1
ORD2 PROD2 1
ORD2 PROD2 1
ORD3 PROD3 1
ORD3 PROD3 1
ORD3 PROD3 1

db<>fiddle

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement