Subject RE: [firebird-support] Can this CTE be optimized further, it takes 16secs but cummu. effect is 20-25min
Author Svein Erling Tysvær
I notice two things, Bhavbhuti:

1) GTT isn't needed, so you can simplify a little bit (though I don't think this will reduce the execution time much):

WITH RECURSIVE Heir(iID, iPK) AS
(SELECT p.iID, p.iID AS iPK FROM mItems p
WHERE p.lHierarchialStock = 1
OR NOT EXISTS (SELECT 1
FROM mItems d
WHERE d.iPID = p.iID)
UNION ALL
SELECT H.iID, p2.iID
FROM mItems p2
JOIN Heir H on p2.iPID = H.iPK)
...

2) I don't like PLAN (HEIR D NATURAL) and PLAN (HEIR P2 NATURAL). Do you have an index for mItems.iPID (and is mItems.iPID defined as integer)? If not, then adding this index ought to make your query a lot faster.

HTH,
Set