Skip to content

Correct the database scope of plan cache removal for ALTER DATABASE - #10502

Open
Rudi Bruchez (rudi-bruchez) wants to merge 1 commit into
MicrosoftDocs:livefrom
rudi-bruchez:fix/database-plan-cache-scope
Open

Rudi Bruchez (rudi-bruchez) wants to merge 1 commit into
MicrosoftDocs:livefrom
rudi-bruchez:fix/database-plan-cache-scope

Conversation

@rudi-bruchez

Copy link
Copy Markdown
Contributor

What's wrong

The SQL Server Remarks sections of ALTER DATABASE and ALTER DATABASE SET options describe changes to individual databases as clearing the plan cache for the instance. The tested changes remove plans associated with the affected database while preserving the same plan handles in other databases.

Both pages also attach the cache-store flush error-log explanation to these database operations. The proposed wording describes compilation of affected queries after cached plans are removed, without implying an instance-wide store flush.

The published ALTER DATABASE SET options page already contains an introductory note describing invalidation for the affected database; the instance-wide statement in Remarks contradicts that note. The Remarks wording is present in the March 2017 migration commit c8e798979d0 and remains on Learn as of November 15, 2026.

Sources:

Evidence

Tested on fresh Linux containers, Developer editions:

Version Build Database compatibility level
SQL Server 2019 CU32-GDR 15.0.4500.2 150
SQL Server 2022 CU27-GDR 16.0.4305.5 160
SQL Server 2025 CU10 17.0.5035.5 170

Each container was limited to 3 GB with MSSQL_MEMORY_LIMIT_MB=2560 and max server memory (MB)=2048. The script creates two fresh databases with AUTO_CLOSE off, Query Store off, and optimize for ad hoc workloads off. It caches one ad hoc plan, one prepared plan and one procedure plan in each database and in master. Before every operation it asserts that all nine sentinel plans exist; afterward it compares their exact plan handles. Configuration and DBCC USEROPTIONS are included in the output.

All three versions produce the same results:

Operation Plans in affected database Plans in the other database and master
Change PAGE_VERIFY to TORN_PAGE_DETECTION Removed Same handles retained
SET READ_ONLY, then SET READ_WRITE (observed separately) Removed each time Same handles retained
MODIFY NAME Removed Same handles retained
Change database collation Removed Same handles retained
MODIFY FILEGROUP DEFAULT Removed Same handles retained
MODIFY FILEGROUP READ_ONLY, then READ_WRITE (observed separately) Removed each time Same handles retained
SET OFFLINE Removed Same handles retained
RESTORE DATABASE WITH REPLACE Removed Same handles retained
Detach and attach Removed Same handles retained
DROP DATABASE Removed Same handles retained
DROP DATABASE of a snapshot Snapshot plans removed Source database, other database and master retain their handles
DBCC FREESYSTEMCACHE ('ALL'), positive control Removed Removed

The script additionally checks that the rename back, return from OFFLINE to ONLINE, and restore after DROP preserve the unrelated sentinel handles. ONLINE is checked after OFFLINE; the affected database has no cached plans at that point.

There are 14 cases and 129 result rows per version, including the snapshot's three plans and its source database's three plans (387 rows across three versions), plus the cleanup scope checks. Assertions cover plan counts, target-plan removal, unrelated-handle retention and the positive control. The script drops its databases, snapshot and procedure created in master.

The test uses disposable instances and sysadmin permissions, with sqlcmd -b -I -C. It performs database detach/attach, restore and drop operations; the names and file paths below are reserved to this reproduction. Use the accompanying runner for an isolated environment.

-- Disposable SQL Server instance only. Run as sysadmin with sqlcmd -b -I -C.
SET NOCOUNT ON;
SELECT @@VERSION AS version;
EXEC sys.sp_configure 'show advanced options',1; RECONFIGURE;
EXEC sys.sp_configure 'optimize for ad hoc workloads',0; RECONFIGURE;
CREATE DATABASE verif_doc_scope_a;
CREATE DATABASE verif_doc_scope_b;
ALTER DATABASE verif_doc_scope_a SET AUTO_CLOSE OFF;
ALTER DATABASE verif_doc_scope_b SET AUTO_CLOSE OFF;
ALTER DATABASE verif_doc_scope_a SET QUERY_STORE = OFF;
ALTER DATABASE verif_doc_scope_b SET QUERY_STORE = OFF;
ALTER DATABASE verif_doc_scope_a ADD FILEGROUP ScopeFG;
ALTER DATABASE verif_doc_scope_a ADD FILE (NAME=N'ScopeFGData', FILENAME=N'/var/opt/mssql/data/verif_doc_scope_fg.ndf', SIZE=8MB) TO FILEGROUP ScopeFG;
SELECT name,compatibility_level,is_auto_close_on,is_query_store_on FROM sys.databases
WHERE name IN (N'verif_doc_scope_a',N'verif_doc_scope_b');
DBCC USEROPTIONS;
GO
USE verif_doc_scope_a;
CREATE TABLE dbo.T(id int NOT NULL PRIMARY KEY,v int NOT NULL);
INSERT dbo.T VALUES(1,10),(2,20);
GO
CREATE PROCEDURE dbo.verif_doc_scope_proc @id int AS
SELECT SUM(a.v+b.v) AS doc_scope_proc FROM dbo.T a JOIN dbo.T b ON a.id=b.id WHERE a.id>=@id;
GO
USE verif_doc_scope_b;
CREATE TABLE dbo.T(id int NOT NULL PRIMARY KEY,v int NOT NULL);
INSERT dbo.T VALUES(1,10),(2,20);
GO
CREATE PROCEDURE dbo.verif_doc_scope_proc @id int AS
SELECT SUM(a.v+b.v) AS doc_scope_proc FROM dbo.T a JOIN dbo.T b ON a.id=b.id WHERE a.id>=@id;
GO
USE master;
GO
CREATE PROCEDURE dbo.verif_doc_scope_master_proc @id int AS
SELECT COUNT_BIG(*) AS doc_scope_master_proc FROM sys.objects a JOIN sys.objects b ON a.object_id=b.object_id WHERE a.object_id>=@id;
GO
CREATE TABLE #before(dbid int,kind nvarchar(20),handle varbinary(64));
CREATE TABLE #after(dbid int,kind nvarchar(20),handle varbinary(64));
CREATE TABLE #results(operation nvarchar(60),dbid int,kind nvarchar(20),before_count int,kept int);
GO
CREATE PROCEDURE #seed AS
BEGIN
 EXEC verif_doc_scope_a.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_adhoc FROM dbo.T a JOIN dbo.T b ON a.id=b.id;';
 EXEC verif_doc_scope_a.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_prepared FROM dbo.T a JOIN dbo.T b ON a.id=b.id WHERE a.id>=@id;',N'@id int',1;
 EXEC verif_doc_scope_a.dbo.verif_doc_scope_proc 1;
 EXEC verif_doc_scope_b.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_adhoc FROM dbo.T a JOIN dbo.T b ON a.id=b.id;';
 EXEC verif_doc_scope_b.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_prepared FROM dbo.T a JOIN dbo.T b ON a.id=b.id WHERE a.id>=@id;',N'@id int',1;
 EXEC verif_doc_scope_b.dbo.verif_doc_scope_proc 1;
 EXEC sys.sp_executesql N'SELECT COUNT_BIG(*) AS doc_scope_master_adhoc FROM sys.objects a JOIN sys.objects b ON a.object_id=b.object_id;';
 EXEC sys.sp_executesql N'SELECT COUNT_BIG(*) AS doc_scope_master_prepared FROM sys.objects a JOIN sys.objects b ON a.object_id=b.object_id WHERE a.object_id>=@id;',N'@id int',1;
 EXEC dbo.verif_doc_scope_master_proc 1;
END;
GO
CREATE PROCEDURE #capture AS
SELECT st.dbid,p.objtype,p.plan_handle
FROM sys.dm_exec_cached_plans p CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) st
WHERE p.cacheobjtype=N'Compiled Plan' AND st.dbid IN (DB_ID(N'verif_doc_scope_a'),DB_ID(N'verif_doc_scope_a_renamed'),DB_ID(N'verif_doc_scope_b'),DB_ID(N'verif_doc_scope_snapshot'),1)
AND ((p.objtype IN(N'Adhoc',N'Prepared') AND st.text LIKE N'%AS doc_scope_%' AND st.text NOT LIKE N'%sys.dm_exec_cached_plans%' AND st.text NOT LIKE N'%CREATE DATABASE%')
 OR (p.objtype=N'Proc' AND st.text LIKE N'%PROCEDURE dbo.verif_doc_scope%'));
GO
BACKUP DATABASE verif_doc_scope_a TO DISK=N'/var/opt/mssql/data/verif_doc_scope_a.bak' WITH INIT;
CREATE TABLE #ops(id int IDENTITY,op nvarchar(60),command nvarchar(max),cleanup nvarchar(max));
INSERT #ops(op,command,cleanup) VALUES
(N'PAGE_VERIFY',N'ALTER DATABASE verif_doc_scope_a SET PAGE_VERIFY TORN_PAGE_DETECTION;',N''),
(N'READ_ONLY',N'ALTER DATABASE verif_doc_scope_a SET READ_ONLY WITH ROLLBACK IMMEDIATE;',N''),
(N'READ_WRITE',N'ALTER DATABASE verif_doc_scope_a SET READ_WRITE;',N''),
(N'RENAME',N'ALTER DATABASE verif_doc_scope_a MODIFY NAME=verif_doc_scope_a_renamed;',N'ALTER DATABASE verif_doc_scope_a_renamed MODIFY NAME=verif_doc_scope_a;'),
(N'COLLATE',N'ALTER DATABASE verif_doc_scope_a COLLATE French_CI_AS;',N''),
(N'FILEGROUP_DEFAULT',N'ALTER DATABASE verif_doc_scope_a MODIFY FILEGROUP ScopeFG DEFAULT;',N''),
(N'FILEGROUP_READ_ONLY',N'ALTER DATABASE verif_doc_scope_a MODIFY FILEGROUP ScopeFG READ_ONLY;',N''),
(N'FILEGROUP_READ_WRITE',N'ALTER DATABASE verif_doc_scope_a MODIFY FILEGROUP ScopeFG READ_WRITE;',N''),
(N'OFFLINE',N'ALTER DATABASE verif_doc_scope_a SET OFFLINE WITH ROLLBACK IMMEDIATE;',N'ALTER DATABASE verif_doc_scope_a SET ONLINE;'),
(N'RESTORE',N'RESTORE DATABASE verif_doc_scope_a FROM DISK=N''/var/opt/mssql/data/verif_doc_scope_a.bak'' WITH REPLACE;',N''),
(N'DETACH_ATTACH',N'EXEC sys.sp_detach_db @dbname=N''verif_doc_scope_a''; CREATE DATABASE verif_doc_scope_a ON (FILENAME=N''/var/opt/mssql/data/verif_doc_scope_a.mdf''),(FILENAME=N''/var/opt/mssql/data/verif_doc_scope_fg.ndf''),(FILENAME=N''/var/opt/mssql/data/verif_doc_scope_a_log.ldf'') FOR ATTACH;',N''),
(N'DROP_DATABASE',N'DROP DATABASE verif_doc_scope_a;',N'RESTORE DATABASE verif_doc_scope_a FROM DISK=N''/var/opt/mssql/data/verif_doc_scope_a.bak'' WITH REPLACE;'),
(N'INSTANCE_CONTROL',N'DBCC FREESYSTEMCACHE (''ALL'');',N'');
DECLARE @i int=1,@last int=(SELECT MAX(id) FROM #ops),@op nvarchar(60),@cmd nvarchar(max),@cleanup nvarchar(max),@target int;
WHILE @i<=@last
BEGIN
 SELECT @op=op,@cmd=command,@cleanup=cleanup FROM #ops WHERE id=@i;
 SET @target=DB_ID(N'verif_doc_scope_a');
 EXEC #seed;
 TRUNCATE TABLE #before; TRUNCATE TABLE #after;
 INSERT #before EXEC #capture;
 IF (SELECT COUNT(*) FROM #before)<>9 THROW 50000,'Expected nine sentinel plans',1;
 EXEC(@cmd);
 INSERT #after EXEC #capture;
 INSERT #results
 SELECT @op,b.dbid,b.kind,COUNT(*),SUM(CASE WHEN a.handle IS NULL THEN 0 ELSE 1 END)
 FROM #before b LEFT JOIN #after a ON a.handle=b.handle GROUP BY b.dbid,b.kind;
 IF @op<>N'INSTANCE_CONTROL' AND EXISTS(SELECT 1 FROM #before b WHERE b.dbid<>@target AND NOT EXISTS(SELECT 1 FROM #after a WHERE a.handle=b.handle))
  THROW 50000,'Operation removed a sentinel plan from another database',1;
 IF @op=N'INSTANCE_CONTROL' AND EXISTS(SELECT 1 FROM #before b JOIN #after a ON a.handle=b.handle)
  THROW 50000,'Positive control did not remove every sentinel',1;
 IF @op<>N'INSTANCE_CONTROL' AND EXISTS(SELECT 1 FROM #before b JOIN #after a ON a.handle=b.handle WHERE b.dbid=@target)
  THROW 50000,'Expected target plans to be removed',1;
 PRINT N'PASS operation: '+@op;
 IF @cleanup<>N''
 BEGIN
  EXEC(@cleanup);
  TRUNCATE TABLE #after;
  INSERT #after EXEC #capture;
  IF EXISTS(SELECT 1 FROM #before b WHERE b.dbid<>@target AND NOT EXISTS(SELECT 1 FROM #after a WHERE a.handle=b.handle))
   THROW 50000,'Cleanup changed a sentinel in another database',1;
  PRINT N'PASS cleanup: '+@op;
 END;
 SET @i+=1;
END;
-- A snapshot has its own plans; dropping it must also preserve its source database.
DECLARE @files nvarchar(max),@create nvarchar(max),@snap int;
SELECT @files=STRING_AGG(CAST(N'(NAME=N'''+name+N''', FILENAME=N''/var/opt/mssql/data/verif_doc_scope_snapshot_'+CAST(file_id AS nvarchar(10))+N'.ss'')' AS nvarchar(max)),N',')
FROM sys.master_files WHERE database_id=DB_ID(N'verif_doc_scope_a') AND type=0;
SET @create=N'CREATE DATABASE verif_doc_scope_snapshot ON '+@files+N' AS SNAPSHOT OF verif_doc_scope_a;';
EXEC(@create);
SET @snap=DB_ID(N'verif_doc_scope_snapshot');
EXEC #seed;
EXEC verif_doc_scope_snapshot.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_adhoc FROM dbo.T a JOIN dbo.T b ON a.id=b.id;';
EXEC verif_doc_scope_snapshot.sys.sp_executesql N'SELECT SUM(a.v+b.v) AS doc_scope_prepared FROM dbo.T a JOIN dbo.T b ON a.id=b.id WHERE a.id>=@id;',N'@id int',1;
EXEC verif_doc_scope_snapshot.dbo.verif_doc_scope_proc 1;
TRUNCATE TABLE #before; TRUNCATE TABLE #after;
INSERT #before EXEC #capture;
IF (SELECT COUNT(*) FROM #before)<>12 THROW 50000,'Expected twelve plans including snapshot',1;
DROP DATABASE verif_doc_scope_snapshot;
INSERT #after EXEC #capture;
INSERT #results
SELECT N'DROP_SNAPSHOT',b.dbid,b.kind,COUNT(*),SUM(CASE WHEN a.handle IS NULL THEN 0 ELSE 1 END)
FROM #before b LEFT JOIN #after a ON a.handle=b.handle GROUP BY b.dbid,b.kind;
IF EXISTS(SELECT 1 FROM #before b WHERE b.dbid<>@snap AND NOT EXISTS(SELECT 1 FROM #after a WHERE a.handle=b.handle))
 THROW 50000,'Dropping snapshot changed a plan outside the snapshot',1;
IF EXISTS(SELECT 1 FROM #before b JOIN #after a ON a.handle=b.handle WHERE b.dbid=@snap)
 THROW 50000,'Snapshot plan unexpectedly retained',1;
PRINT 'PASS operation: DROP_SNAPSHOT';
SELECT operation,dbid,kind,before_count,kept FROM #results ORDER BY operation,dbid,kind;
IF (SELECT COUNT(*) FROM #results)<>129 THROW 50000,'Expected 129 result rows',1;
DROP PROCEDURE dbo.verif_doc_scope_master_proc;
DROP DATABASE verif_doc_scope_a;
DROP DATABASE verif_doc_scope_b;
PRINT 'PASS: 14 cases, 129 sentinel checks, plus cleanup scope checks; databases and master procedure dropped';

Change

The Remarks sections say that the listed options can remove cached plans for the affected database. They describe the compilation impact on subsequent executions of affected queries. The list uses the valid MODIFY NAME spelling, and PAGE_VERIFY replaces ONLINE in the SET-options list to match the measured changes and the existing ALTER DATABASE list.

The general operation lists say that the operations can remove cached plans, without claiming an instance-wide flush. The transaction-log rebuild scenario remains in those lists, but was not tested and no scope-specific claim is added for it. Azure SQL Managed Instance and Azure SQL Database sections are unchanged; those products were not tested.

The separate AUTO_CLOSE paragraph is covered by PR #10431: #10431. This proposal does not duplicate its rewrite.

Changes to a database remove its cached plans while preserving plans in other databases. Describe the affected database and its subsequent compilations instead of an instance-wide cache-store flush.
@prmerger-automator

Copy link
Copy Markdown
Contributor

Rudi Bruchez (@rudi-bruchez) : Thanks for your contribution! The author(s) and reviewer(s) have been notified to review your proposed change.

@learn-build-service-prod

Copy link
Copy Markdown
Contributor

Learn Build status updates of commit b8223fb:

✅ Validation status: passed

File Status Preview URL Details
docs/t-sql/statements/alter-database-transact-sql-set-options.md ✅Succeeded
docs/t-sql/statements/alter-database-transact-sql.md ✅Succeeded

For more details, please refer to the build report.

@ttorble

Copy link
Copy Markdown
Contributor

Umachandar Jayachandran (@uc-msft)

Can you review the proposed changes?

Due to the upcoming conference, all merging and publishing is on hold until the morning of November 17.

Important: When the changes are ready for publication, adding a #sign-off comment is the best way to signal that the PR is ready for the review team to merge.

#label:"aq-pr-triaged"
@MicrosoftDocs/public-repo-pr-review-team

@prmerger-automator prmerger-automator Bot added the aq-pr-triaged tracking label for the PR review team label Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants