From f922d0e1eed82a1b1ea1df86389ac0131d38adf3 Mon Sep 17 00:00:00 2001 From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com> Date: Tue, 24 Mar 2026 10:53:47 -0400 Subject: [PATCH] sp_QuickieStore: use EXISTS pattern in final plan OUTER APPLY The JOIN pattern in the OUTER APPLY wasn't getting a good plan. EXISTS with the semi-join against #hi_id_staging_plans lets the optimizer pick a better strategy for the correlated subquery. Tested on SQL2022. Co-Authored-By: Claude Opus 4.6 (1M context) --- sp_QuickieStore/sp_QuickieStore.sql | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/sp_QuickieStore/sp_QuickieStore.sql b/sp_QuickieStore/sp_QuickieStore.sql index 597f9209..f9034526 100644 --- a/sp_QuickieStore/sp_QuickieStore.sql +++ b/sp_QuickieStore/sp_QuickieStore.sql @@ -5606,10 +5606,15 @@ OUTER APPLY qsp.last_execution_time DESC ), qsp.query_plan - FROM #hi_id_staging_plans AS sp - JOIN ' + @database_name_quoted + N'.sys.query_store_plan AS qsp - ON qsp.plan_id = sp.plan_id - WHERE sp.query_hash = o.query_hash + FROM ' + @database_name_quoted + N'.sys.query_store_plan AS qsp + WHERE EXISTS + ( + SELECT + 1/0 + FROM #hi_id_staging_plans AS sp + WHERE qsp.plan_id = sp.plan_id + AND sp.query_hash = o.query_hash + ) ) AS qp0 WHERE qp0.n = 1 ) AS qp