From f5b2899189f361b40a6f48276abc3fbe3425ba10 Mon Sep 17 00:00:00 2001 From: Erik Darling <2136037+erikdarlingdata@users.noreply.github.com> Date: Wed, 25 Mar 2026 05:41:42 -0400 Subject: [PATCH] sp_IndexCleanup: scope #usage_stats staging to #filtered_objects Adds EXISTS filter against #filtered_objects when populating #usage_stats, so only indexes on objects we're analyzing are staged instead of every touched index in the database. Tested on SQL2022. Co-Authored-By: Claude Opus 4.6 (1M context) --- sp_IndexCleanup/sp_IndexCleanup.sql | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/sp_IndexCleanup/sp_IndexCleanup.sql b/sp_IndexCleanup/sp_IndexCleanup.sql index 65527fff..8ffeedde 100644 --- a/sp_IndexCleanup/sp_IndexCleanup.sql +++ b/sp_IndexCleanup/sp_IndexCleanup.sql @@ -2167,7 +2167,15 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. us.last_user_lookup, us.last_user_update FROM sys.dm_db_index_usage_stats AS us - WHERE us.database_id = @current_database_id; + WHERE us.database_id = @current_database_id + AND EXISTS + ( + SELECT + 1/0 + FROM #filtered_objects AS fo + WHERE fo.database_id = @current_database_id + AND fo.object_id = us.object_id + ); SELECT @sql = N'