Skip to content

Commit aab7044

Browse files
authored
JobHistory_Upd - performance fix
The performance optimization for MAX(instance_id) is subject to plan variation. Changing the OUTER APPLY to use TOP(1) instead of MAX should allow us to get the query plan we want more reliably.
1 parent 62a9612 commit aab7044

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

DBADashDB/dbo/Stored Procedures/JobHistory_Upd.sql

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,19 @@ FROM @JobHistory T
2828
WHERE NOT EXISTS(SELECT 1 FROM dbo.Jobs J WHERE J.job_id = T.job_id AND J.InstanceID = @InstanceID)
2929
GROUP BY job_id
3030

31+
/*
32+
Performance optimization:
33+
The goal is for the query optimizer to seek on InstanceID within each partition, then perform a backward ordered scan to get the MAX instance_id for each partition very efficiently.
34+
We then return the MAX across partitions. Older partitions could probably be skipped, but the cost of including them is small.
35+
*/
3136
DECLARE @max_instance_id INT=-1
3237
SELECT TOP(1) @max_instance_id = ISNULL(MAX(m.instance_id),-1)
3338
FROM sys.partitions p
34-
OUTER APPLY(SELECT MAX(instance_id) AS instance_id
35-
FROM dbo.JobHistory
39+
OUTER APPLY(SELECT TOP(1) instance_id
40+
FROM dbo.JobHistory
3641
WHERE InstanceID = @InstanceID
3742
AND $PARTITION.PF_JobHistory(RunDateTime) = p.partition_number
43+
ORDER BY instance_id DESC
3844
) m
3945
WHERE p.object_id = OBJECT_ID('dbo.JobHistory')
4046
AND p.index_id=1
@@ -166,4 +172,4 @@ EXEC dbo.CollectionDates_Upd @InstanceID = @InstanceID,
166172
@Reference = @Ref,
167173
@SnapshotDate = @SnapshotDate
168174

169-
COMMIT
175+
COMMIT

0 commit comments

Comments
 (0)