Back to all posts

Deploying SQL Server Schema Changes Safely

Why one ALTER TABLE can freeze a busy SQL Server, the two settings that stop it, and how to check the change before and after it runs.

On this page
Words in this article

Words in this article

DDL
Data Definition Language: statements that change a table's structure, such as ALTER TABLE.
Lock
How SQL Server keeps two sessions from changing the same thing at once.
Sch-M lock
Schema modification lock: taken by DDL, blocks all other use of the table.
Sch-S lock
Schema stability lock: taken by every query so the structure cannot change under it.
Connection pool
The fixed set of database connections that an application's requests share.
Transaction
A group of statements that succeed or fail together.
Online
Queries keep running while the change works.
Design model
DbSchema's own copy of your schema, kept in a .dbs file.
.dacpac
A package that describes a schema, used by Microsoft's SqlPackage.

The short answer

A schema change, or DDL (Data Definition Language), is a statement that changes a table's structure, such as ALTER TABLE. It can stop a busy SQL Server application for minutes. The change itself is rarely slow. The damage comes from the queries that wait while the change waits for its lock. A lock is how SQL Server keeps two sessions from changing the same thing at once. Three habits prevent the damage:

  1. Start every script with two settings

    SET LOCK_TIMEOUT stops the change from waiting forever. SET XACT_ABORT ON undoes the whole change if one statement fails.

  2. Pick statements that do not rewrite the table

    Some forms of ALTER TABLE and ALTER INDEX finish at once or let queries keep running.

  3. Compare before and after

    Check what the script will change before it runs, and check that the database matches the plan afterwards.

What DbSchema adds to a SQL Server deployment

Why DbSchema

See the steps ↓

DbSchema keeps its own copy of your schema, called the design model, in a .dbs file. Schema synchronization compares that model with a database and lists every difference. From that list, DbSchema writes the change script for you and checks the result after the release. You still add the two settings from the first habit yourself. That takes two lines, and it still beats writing every ALTER by hand, because the script cannot forget a column or an index that the comparison found. Schema synchronization and saving the model to a file need DbSchema Pro.

  • The script written for you

    Schema synchronization shows one row per difference. In each row you choose which version to keep, the model's or the database's, and DbSchema writes the SQL for it.

  • A script you read first

    Generate SQL script writes the statements without running them. You choose where they go, the SQL Editor or a file, and add the two settings on top.

  • One statement at a time

    Commit in the database runs the statements one by one. For each one you press Execute to run it or Skip to leave it out.

  • The design in Git

    The .dbs file goes into Git next to your code. Git Collaboration shows what changed in the model between commits.

  • Proof that the release landed

    After the deployment, Refresh Model from Database compares again. “Schemas are identical” means the database matches the plan.

Then, in DbSchema:CompareGenerate SQL scriptRefresh Model from Database

How SQL Server locks a table during DDL

SQL Server uses two kinds of schema lock[1]:

  • Sch-S, schema stability. Every query takes it while it runs, so the table's structure cannot change under it.
  • Sch-M, schema modification. DDL takes it. While SQL Server holds it, no other session can use the table.
Four requests for the table Sales.Orders in order: a long report holds a Sch-S lock, an ALTER TABLE waits for its Sch-M lock, and two new SELECT queries from the app wait behind the ALTER TABLE

The trouble starts when a long report is still reading the table. The ALTER TABLE must wait for the report to finish. New queries from the application then queue behind the waiting ALTER TABLE. SQL Server does not let them jump ahead of a pending Sch-M request, which blocks all other access[1]. Microsoft warns that waiting for a Sch-M lock can increase query latency and cause time-outs for the whole workload[6].

Your application talks to the database through a connection pool, a fixed set of connections that its requests share. Every waiting query holds one of them. Within seconds the pool is empty, and the application stops answering.

State-based versus artifact-based SQL Server deployments

There are two ways to ship schema changes:

ApproachWhat you shipWhat runs in production
State-basedA description of the target schemaSQL that a tool works out at deployment time
Artifact-basedA versioned SQL scriptThe exact script your team reviewed

Microsoft's own state-based tool is SqlPackage. It updates a database to match a .dacpac file, a package that describes the schema[2]. DbSchema sits between the two. It compares the model with the database like a state-based tool, but the result is a script that you read and keep, like an artifact-based release. Schema Versioning for SQL Server covers the script side in more detail.

What to have in place before the first script

  • The planned schema in a file that lives in Git, so every change has a history.
  • A connection to each environment, development, staging and production, with the right to run DDL.
  • A comparison of the planned schema with the target database, and the script it produces, read line by line.

Setting LOCK_TIMEOUT and XACT_ABORT before any DDL

A new connection waits for a lock forever. LOCK_TIMEOUT starts at -1, which means no time limit[3]. Set LOCK_TIMEOUT to 5000 milliseconds, and the waiting ALTER TABLE fails after five seconds with a lock time-out error. The ALTER TABLE gives up its pending Sch-M request, so the queries behind it get their Sch-S locks and run.

A transaction groups statements so that they succeed or fail together. XACT_ABORT is OFF by default. With OFF, SQL Server may roll back only the failing statement and carry on with the rest. With ON, a run-time error rolls back the entire transaction[4].

Put both settings at the top of every deployment script:

SET XACT_ABORT ON;
SET LOCK_TIMEOUT 5000;

BEGIN TRANSACTION;

ALTER TABLE Sales.Orders
ADD LoyaltyPoints int NULL;

COMMIT TRANSACTION;

SET LOCK_TIMEOUT -1;

If the lock does not come within five seconds, the script stops and nothing is changed. Run it again when the report has finished.

Adding columns, constraints and indexes without a rewrite

Some statements only update the table's description. Others read or rewrite every row while they hold the lock. Choose the first kind where you can:

ChangeWhat to writeWhat to know
New NOT NULL columnA default that is the same for every row, such as a fixed valueOnline in Enterprise edition from SQL Server 2012[5]
New CHECK or FOREIGN KEYWITH NOCHECK, then check laterSkips reading every existing row
Index rebuildONLINE = ONQueries keep running, but not every edition has it[6]

Online means that queries keep running while the change works. The rule behind the first row: a fixed default can be stored once, in the table's description, so no row is touched. A default such as NEWID() gives every row a different value, so SQL Server must write it into every row. That ALTER TABLE always runs offline, under a Sch-M lock for its whole duration[5].

A constraint added WITH NOCHECK does not read the existing rows:

ALTER TABLE Sales.Orders WITH NOCHECK
ADD CONSTRAINT CK_Orders_TotalAmount CHECK (TotalAmount >= 0);

The constraint is then not trusted. The query optimizer, the part of SQL Server that plans queries, ignores it until you check it[5]. The later check reads every row and holds a lock while it runs, so run it in a quiet hour:

ALTER TABLE Sales.Orders WITH CHECK CHECK CONSTRAINT CK_Orders_TotalAmount;

An online rebuild still needs a short Sch-M lock at its start and end. Three options in the statement below control that wait[6]:

  • WAIT_AT_LOW_PRIORITY makes the rebuild wait at low priority, so normal queries go first.
  • MAX_DURATION = 2 MINUTES is how long it waits like that.
  • ABORT_AFTER_WAIT = SELF stops the rebuild when the two minutes are over, and leaves the queries alone.

RESUMABLE = ON lets you pause the rebuild and resume it later, from SQL Server 2017.

ALTER INDEX IX_Orders_CustomerID ON Sales.Orders
REBUILD WITH (
  ONLINE = ON (
    WAIT_AT_LOW_PRIORITY (MAX_DURATION = 2 MINUTES, ABORT_AFTER_WAIT = SELF)
  ),
  RESUMABLE = ON
);

Where SQL Server deployments usually break

  • An online option on an edition without it. An edition is a SQL Server product level, such as Enterprise or Standard. Online index operations are not in every edition[6]. A script that worked on a test server can then fail on production. Check the production edition first.
  • No lock time-out. The ALTER TABLE waits behind a report, and the application stops answering.
  • XACT_ABORT left OFF. One statement fails, the others run, and the schema ends up half changed.

The same risks exist on other engines. PostgreSQL Schema Migration: Deploying Changes Safely covers them for PostgreSQL.

Generate and verify the migration script in DbSchema

Six steps of a safe deployment with DbSchema: the design model in Git, compare with the database, Generate SQL script, add SET LOCK_TIMEOUT and SET XACT_ABORT ON, run it in the SQL Editor, and compare again until DbSchema says Schemas are identical

Generating the migration script from a schema comparison

  1. Connect and choose Compare

    Connect to the SQL Server database. DbSchema asks how to bring the model and the database together, with three choices: Compare, then decide difference by difference; Write the model into the database; and Skip. Choose Compare, then decide difference by difference.

  2. Decide each difference Pro

    The Synchronize Model and Database dialog opens. Each row is one difference. In the Action column, click the side whose version you keep, the model or the database. Ignore leaves the row as it is.

  3. Read the SQL

    Select a row to see its SQL in the lower pane.

  4. Generate the script

    Press Generate SQL script at the bottom of the dialog. In the Choose Output dialog, pick SQL Editor.

  5. Add the guards and run

    Add SET XACT_ABORT ON; and SET LOCK_TIMEOUT 5000; at the top, read the script, and run it.

The DbSchema Synchronize Model and Database dialog with three differences: birth_date in customers and the rename of carrier_name set to the database, the table suppliers set to the model, and the ALTER TABLE statement of birth_date below

Confirming the deployed schema matches the model

After the script ran, press Refresh in the toolbar, or choose Database → Refresh Model from Database. If nothing differs, DbSchema says "Schemas are identical". Any other result shows exactly which column, index or constraint did not land. Finding schema drift between environments explains how to use the same check across staging and production.

DbSchema reporting that the schemas are up to date in the database, the result a comparison after the deployment should return

Download DbSchema, connect to your SQL Server database, and compare your model with it before the next release.

Frequently asked questions

Does DbSchema change the database while I compare?

No, comparing only reads the database, and so does opening the model. The database changes only when you run a script, or press Execute for a statement.

Can I keep the script for my deployment pipeline?

Yes. In the Choose Output dialog of Generate SQL script, pick File instead of SQL Editor. Add the two settings, commit the file, and let the pipeline run it.

Sources

  1. Microsoft: Transaction locking and row versioning guide
  2. Microsoft: SqlPackage Publish
  3. Microsoft: SET LOCK_TIMEOUT
  4. Microsoft: SET XACT_ABORT
  5. Microsoft: ALTER TABLE
  6. Microsoft: ALTER INDEX

Compare the model before you deploy

DbSchema reverse-engineers your SQL Server database, shows what differs from your design model, and generates the migration script you review before it runs. Schema synchronization needs DbSchema Pro; the download includes a free trial.