Skip to content

Use CREATE INDEX with DROP_EXISTING=ON for index facet changes (SQL Server) - #38271

Merged
AndriySvyryd merged 4 commits into
dotnet:mainfrom
m-x-shokhzod:perf/sqlserver-drop-existing-index
Jun 9, 2026
Merged

AndriySvyryd merged 4 commits into
dotnet:mainfrom
m-x-shokhzod:perf/sqlserver-drop-existing-index

Conversation

@m-x-shokhzod

Copy link
Copy Markdown
Contributor

When an index facet changes (fill factor, sort order, uniqueness, filter, columns), MigrationsModelDiffer produces a DropIndexOperation + CreateIndexOperation pair, which the SQL Server generator emits as two statements:

DROP INDEX [IX_People_X] ON [People];
CREATE UNIQUE INDEX [IX_People_X] ON [People] ([X]);

This is suboptimal: during the drop, queries can't use the index → potentially full table scans, and on large tables the gap can be significant.

SQL Server supports CREATE INDEX ... WITH (DROP_EXISTING = ON) since SQL Server 2008, which:

  • Atomically replaces the old index in a single statement
  • Lets queries continue using the old index while the new one is being built — no un-indexed gap

After

CREATE UNIQUE INDEX [IX_People_X] ON [People] ([X]) WITH (DROP_EXISTING = ON);

Implementation

The rewrite lives entirely in the SQL Server provider:

  • New internal annotation SqlServerAnnotationNames.UseDropExisting
  • New helper SqlServerMigrationsSqlGenerator.RewriteDropAndCreateIndexAsDropExisting (called from RewriteOperations, alongside the existing FixLegacyTemporalAnnotations) — detects Drop+Create pairs for the same (Name, Table, Schema), removes the drop from the operation list, and marks the create with UseDropExisting = true
  • IndexOptions reads the annotation and adds DROP_EXISTING = ON to the WITH (...) clause alongside FILLFACTOR, ONLINE, SORT_IN_TEMPDB, DATA_COMPRESSION

Limited to standard indexes — memory-optimized, full-text, and vector indexes use different syntax/restrictions and fall back to the existing drop+create path.

MigrationsModelDiffer is unchanged; the differ still emits Drop+Create as before. Other providers (MySQL, PostgreSQL, SQLite, Cosmos) are unaffected.

Tests

Test Type Verifies
Alter_index_make_unique functional (override) Existing test — SQL expectation updated to single-statement form
Alter_index_change_sort_order functional (override) Existing test — SQL expectation updated
Alter_index_fill_factor_uses_drop_existing functional (new) FILLFACTOR change collapses to WITH (FILLFACTOR = 90, DROP_EXISTING = ON)
Alter_index_filter_uses_drop_existing functional (new) Filter change collapses to WITH (DROP_EXISTING = ON), filter rendered after WHERE

All 4 tests pass end-to-end against a real SQL Server instance (verified locally against Azure SQL Edge on Apple Silicon ARM64; the CI matrix will additionally verify against SqlServer 2019/2022/2025).

Full regression sweep: EFCore.SqlServer.Tests 1335/1335, SqlServerMigrationsSqlGeneratorTest 124/124, MigrationsSqlServerTest index tests 34/34.

Fixes #35067

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves SQL Server migration generation for index facet changes by collapsing DropIndexOperation + CreateIndexOperation pairs into a single CREATE INDEX ... WITH (DROP_EXISTING = ON) statement, avoiding an “unindexed gap” during index rebuilds.

Changes:

  • Added an internal SqlServerAnnotationNames.UseDropExisting annotation and logic to emit DROP_EXISTING = ON in IndexOptions.
  • Introduced a SQL Server–specific rewrite step to remove matching DropIndexOperations and mark the corresponding CreateIndexOperations for DROP_EXISTING.
  • Updated/added SQL Server functional tests to assert the single-statement behavior for uniqueness, sort order, fill factor, and filter changes.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
test/EFCore.SqlServer.FunctionalTests/Migrations/MigrationsSqlServerTest.cs Updates existing SQL assertions and adds new functional tests to validate DROP_EXISTING = ON generation.
src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs Adds index drop/create rewrite logic and emits DROP_EXISTING = ON when annotated.
src/EFCore.SqlServer/Metadata/Internal/SqlServerAnnotationNames.cs Introduces a new internal annotation name used to trigger DROP_EXISTING emission.

m-x-shokhzod added a commit to m-x-shokhzod/efcore that referenced this pull request May 23, 2026
Addresses Copilot review on dotnet#38271:

- The rewrite previously matched any DropIndexOperation with any
  CreateIndexOperation of the same (Name, Table, Schema) regardless of
  position. If an AlterColumnOperation on the indexed column sat between
  them, removing the drop would re-introduce the old index before the
  ALTER COLUMN ran and break the migration. Switch to a positional scan
  so only adjacent (i, i+1) pairs collapse.

- IsMemoryOptimized was previously called with `model: null`, mixing
  named/positional style and disabling the model-based fallback. Thread
  the `model` parameter from RewriteOperations into the rewrite method
  and call IsMemoryOptimized fully positionally with the real model.

Add regression test Alter_index_with_non_adjacent_drop_and_create_keeps_separate
which forces a DropIndex + AlterColumn + CreateIndex sequence and
asserts the drop survives and no DROP_EXISTING is emitted.
Comment on lines +2694 to +2699
if (migrationOperations.Count < 2
|| !migrationOperations.OfType<DropIndexOperation>().Any()
|| !migrationOperations.OfType<CreateIndexOperation>().Any())
{
return migrationOperations;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this short-circuit, it doesn't actually save much time compared to the loop below.

{
continue;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can call i++ here, since we know that the next operation cannot be a DropIndexOperation

…erver)

When an index facet changes (fill factor, sort order, uniqueness, filter,
columns), the migration model differ produces a DropIndexOperation +
CreateIndexOperation pair. On SQL Server this can be collapsed into a single
`CREATE INDEX ... WITH (DROP_EXISTING = ON)`, which:

- Lets queries continue using the old index while the new one is being built
  (no un-indexed gap during a long rebuild on large tables)
- Atomically replaces the old index in a single statement

The rewrite lives in SqlServerMigrationsSqlGenerator.RewriteOperations
(new helper RewriteDropAndCreateIndexAsDropExisting). The matching
DropIndexOperation is removed from the operation list and the
CreateIndexOperation is marked with a new internal annotation
SqlServerAnnotationNames.UseDropExisting, which IndexOptions reads to
emit DROP_EXISTING = ON in the WITH clause.

Limited to standard indexes — memory-optimized, full-text, and vector
indexes use different syntax/restrictions and fall back to the existing
drop+create path.

MigrationsModelDiffer is unchanged; the differ still emits Drop+Create as
before. Other providers are unaffected.

Fixes dotnet#35067
Addresses Copilot review on dotnet#38271:

- The rewrite previously matched any DropIndexOperation with any
  CreateIndexOperation of the same (Name, Table, Schema) regardless of
  position. If an AlterColumnOperation on the indexed column sat between
  them, removing the drop would re-introduce the old index before the
  ALTER COLUMN ran and break the migration. Switch to a positional scan
  so only adjacent (i, i+1) pairs collapse.

- IsMemoryOptimized was previously called with `model: null`, mixing
  named/positional style and disabling the model-based fallback. Thread
  the `model` parameter from RewriteOperations into the rewrite method
  and call IsMemoryOptimized fully positionally with the real model.

Add regression test Alter_index_with_non_adjacent_drop_and_create_keeps_separate
which forces a DropIndex + AlterColumn + CreateIndex sequence and
asserts the drop survives and no DROP_EXISTING is emitted.
- Remove the early-out short-circuit in RewriteDropAndCreateIndexAsDropExisting:
  the scan loop already returns the operations unchanged when there is no
  adjacent DropIndex+CreateIndex pair, so the guard saved little.
- After collapsing an adjacent pair, advance the loop index past the matched
  CreateIndexOperation, which cannot itself begin a new pair.
Rebasing onto main surfaced two interactions:

- SQL Server JSON indexes (dotnet#38302) are emitted as a DropIndex + CreateIndex
  pair, and CREATE JSON INDEX supports WITH (DROP_EXISTING = ON), so the
  existing rewrite collapses them like any other index. Update the
  Change_json_index_path[_index] tests to expect the single-statement form.
- xUnit v3 makes the parameterless ConditionalFact obsolete; use [Fact] for the
  unconditional DROP_EXISTING tests, matching the base MigrationsTestBase.
@m-x-shokhzod
m-x-shokhzod force-pushed the perf/sqlserver-drop-existing-index branch from ee5bc4d to 6f51ef5 Compare June 9, 2026 15:00

@AndriySvyryd AndriySvyryd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution!

@AndriySvyryd
AndriySvyryd merged commit 3451cde into dotnet:main Jun 9, 2026
24 of 25 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone Jun 12, 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.

SQL Server: instead of dropping/creating indexes, use CREATE INDEX with DROP EXISTING=ON

3 participants