Changing the Schema Without Losing Data
Change a Live Table Safely
The App Is Still Running
Rename a column in one shot and there's a gap where the old code is asking for a column that's gone. The safe way has a boring name, expand and contract, and it works in both worlds:
- Expand: add the new column. The old one stays. Nothing breaks.
- Write both: deploy code that fills both columns.
- Backfill: copy the old rows over, in batches.
- Switch: deploy code that reads the new column and no longer needs the old one.
- Contract: later, drop the old column.
Each step is small, and the early ones are easy to back out of. Rush step 5 and you lose the way back.
Expand
ALTER TABLE dbo.Customers ADD FullName nvarchar(150) NULL;
Allow NULL at first. Existing rows have nothing to put there, so adding a required column with no default fails on a table that has rows in it.
Backfill
DECLARE @rows int = 1;
WHILE @rows > 0
BEGIN
UPDATE TOP (2000) dbo.Customers
SET FullName = Name
WHERE FullName IS NULL;
SET @rows = @@ROWCOUNT;
END;
Why batches? One giant UPDATE can lock the whole table until it's done. Small batches let everybody else in between. This loop ends because Name is required; if it could be NULL, those rows would match forever and it would never stop. That's exactly the kind of thing to ask the AI about.
Prove It, Then Tighten
SELECT COUNT(*) AS Missing
FROM dbo.Customers
WHERE FullName IS NULL OR FullName <> Name;
-- must be 0
ALTER TABLE dbo.Customers
ALTER COLUMN FullName nvarchar(150) NOT NULL;
Run the check by itself. Only go on when it says 0.
Rehearse It
In SQL Server, most schema changes can be undone inside a transaction, the same as data changes. On a copy of the database:
SET XACT_ABORT ON;
BEGIN TRANSACTION;
ALTER TABLE dbo.Customers ADD Tier varchar(20) NOT NULL
CONSTRAINT DF_Customers_Tier DEFAULT 'Standard';
-- look at the result
SELECT TOP (5) * FROM dbo.Customers;
ROLLBACK TRANSACTION;
Steering the AI
Change: rename Customers.Name to FullName and widen it to
nvarchar(150). SQL Server 2022 Standard. 2 million rows. The
app stays up.
Give me separate scripts for expand, backfill and contract.
For each one tell me:
- what it locks, and for roughly how long
- what happens if it fails halfway
- how to undo it, or that it can't be undone
- the query that proves it worked
List every view, procedure, index and report that might use
the old column, and the query you'd use to find them.
Then check what it tells you. "What it locks" depends on your version and edition. For one, building an index with ONLINE = ON needs Enterprise, Developer or Azure SQL. On Standard, a normal index build blocks writes until it finishes.
A rollback script for a dropped column gives you the column back, empty. Only a backup gives you the data. Before any contract step, have a backup you've actually restored at least once.
Why add the new column first and drop the old one much later?