I have two tables, T1 and T2 with 1 trigger on each. Following occurs:
-- Execute Query 1, say Q1
UPDATE Y.T1
SET name='name'
WHERE id=0 ;
this results in trigger (Trigger1) firing query:
UPDATE Y.T2 SET IsFlat = 0 where id = -1;
---- few seconds later, i execute query Q2:
WITH X AS (
select TV0.Id, row_number() over(
partition by coalesce(TV0.ParentId, 0)
order by UPPER(NAME)
) as RN
from Y.T2 TV0
where TV0.TagId = 604
)
update Y.T2 TV
set SortOrder = X.RN
from X
where X.Id = TV.Id ;
this results in trigger (Trigger2) being fired:
begin
-- get timestamp say Time1
for rec in SELECT n.id, n.tagId, n.parentId as newParentId, o.parentId as oldParentId
FROM new_table n JOIN old_table o on n.id = o.id
and o.parentId != n.parentId
loop. -- it never enters this loop, mycounter when printed always returns 0
mycounter:=mycounter+1;
end loop;
-- get Timestamp say Time2
end;
Query 2 takes 30 seconds If Q1 precedes it. Otherwise it finishes in less than 2 sec. Query 2 takes 30 seconds because of the trigger Trigger2, which consumes almost 28-30 sec to execute.
Query 2 by itself finishes in 2 sec when not preceded by Query1.
Execution plan shows trigger taking time ~28 sec.
If i replace the join in trigger
FROM new_table n JOIN old_table o
to use either of one table, which eliminates join, query comes back in ~2-3 sec. So we know join (defined in trigger) is slow if it succeeds Query 1. Why would that be the case?
I also tried update statement to replace Query 2 to:
update Y.T2 TV
set SortOrder = 1
where SortOrder = 1;
and query join finishes in time. I add another trigger with same join condition and query time increases to 2X say ~60 sec in this case.