> codebench_TOOL: HomeLOCAL-ONLY⌘K Switch

SQLite Column Rename: Keep Your Data When a Schema Diff Suggests ADD and DROP

A schema diff suggests ADD and DROP for a simple rename. Rehearse both paths in an in-memory SQLite database and prove which one keeps each copy on its shelf.

·6 min readAbout the maintainer
A library catalog card for copy 17: the heading changes from shelf_code to location_code, but the value B-14 must stay.

Copy 17 of an orchestral score is on shelf B-14. The library is adding storage drawers, so the catalog editor wants the field called location_code instead of shelf_code. Nobody has moved the score. On Monday morning, typing 17 into the catalog should still tell a musician to go to B-14.

That last sentence is a better migration requirement than “the table should have a column named location_code.” Two migrations can produce the same table definition and send the musician to very different places. We'll generate one candidate from a schema diff, try it on four catalog records, and compare it with a rename. Everything that changes data in this exercise happens in a disposable SQLite database.

Give the schema comparison one difference to explain

Open DDL Compare, select SQLite under Dialect, and paste the following into Current Schema (DDL). DDL describes the shape of the table; this input does not contain the address of a live database or any of its rows.

CREATE TABLE score_copies (
  copy_id INTEGER PRIMARY KEY,
  shelf_code TEXT
);

For a quick control, put the same definition on the right and choose Compare DDL. There should be no differences. Choose Edit to return to the inputs. This time replace only Target Schema (DDL) with the definition below. Keep Generate DROP checked and compare again.

CREATE TABLE score_copies (
  copy_id INTEGER PRIMARY KEY,
  location_code TEXT
);

The generated comments separate additions from removals. Read just the two executable statements for a moment. These are candidate statements for the experiment, not instructions to run against a catalog you care about:

ALTER TABLE "score_copies" ADD COLUMN "location_code" TEXT;
ALTER TABLE "score_copies" DROP COLUMN "shelf_code";

The comparison found one name on the right that wasn't on the left, and one on the left that isn't on the right. Neither statement says to carry a value across. The new column is nullable and has no explicit default, so existing rows read as NULL in that column. Dropping the old column then removes the place that still had the shelf label.

Decide whether this is actually a rename

Why not infer a rename when two text fields occupy the same position? Imagine the same developer hands you the same two definitions, but this time location_code means a barcode issued by a central warehouse. B-14 is not one of those barcodes. Copying it would quietly manufacture a plausible-looking but wrong location. Position and type are clues to ask a question, not evidence of the answer.

Ask the catalog editor what should happen to copy 17 on the day of the change. “It still says B-14” supports a rename. “Look up its warehouse barcode” calls for a mapping, including a decision for copies that don't have a barcode yet. Here we'll use the first answer. The invariant to test is that each copy ID keeps its old value, including the absence of a value. A count of rows or a list of column names cannot establish that.

Uncheck Generate DROP and run the comparison once more. For these inputs only the addition remains. That is less destructive, but it isn't a rename either: the old labels would still exist under shelf_code, while a reader using location_code would see an empty field. Turning off removal can buy time to investigate. It doesn't tell a tool what the data means.

Build a rehearsal small enough to inspect by eye

Start sqlite3 :memory: in a terminal. Use SQLite 3.35.0 or later for this exercise because the first candidate uses DROP COLUMN. Keep this one session open through both trials. Run the current, not the target, CREATE TABLE statement above. Then enter this setup:

INSERT INTO score_copies VALUES
  (17, 'B-14'), (18, NULL), (19, ''), (20, 'B-14');

CREATE TEMP TABLE expected AS
  SELECT copy_id, shelf_code AS label FROM score_copies;

SAVEPOINT trial;

The four rows are deliberately unlike a neat demonstration with four distinct labels. Copy 18 has no recorded location. Copy 19 has an empty string from an old import. Copies 17 and 20 share a shelf, as real scores might. If you test only a row whose value was already NULL, the broken migration looks correct. If you compare only distinct labels, you can't tell whether the right copy kept its address.

The temporary table is a witness: it holds the original pairs under a neutral column name, independently of changes to score_copies. The savepoint comes after that snapshot so we can rewind the trial without losing the evidence. An in-memory session is handy here because closing it discards the exercise, but it also means that opening a second terminal gives you a different, empty database.

Try the generated candidate and measure what it lost

Run the displayed ADD COLUMN and DROP COLUMN pair in this memory session, not the add-only preview. Now ask for the labels. Use quote() for display: it makes an empty string visible as '' and a missing value visible as NULL, instead of letting both look like blank cells in a terminal.

SELECT copy_id, quote(location_code) AS stored_label
FROM score_copies ORDER BY copy_id;

All four IDs are still there, but all four labels now read NULL. No row-count alarm would have gone off. To turn that observation into a repeatable check, compare the pairs in both directions:

WITH missing AS (
  SELECT copy_id, label FROM expected
  EXCEPT
  SELECT copy_id, location_code FROM score_copies
), unexpected AS (
  SELECT copy_id, location_code FROM score_copies
  EXCEPT
  SELECT copy_id, label FROM expected
)
SELECT (SELECT count(*) FROM missing) AS missing_pairs,
       (SELECT count(*) FROM unexpected) AS unexpected_pairs;

You should get 3 missing pairs and 3 unexpected pairs, not four. Copy 18 still has precisely the value it started with. SQLite's EXCEPT treats two NULL values as equal for this comparison. Including the primary key means that the two B-14 records are different pairs; neither can hide the loss of the other. Checking in reverse also catches a new ID that was never in the snapshot. A one-way check could miss that extra record entirely.

Copy 17 starts at B-14. Adding a fresh column and dropping the old one leaves its new label NULL; renaming the old column leaves it B-14.
Both trials end with a field named location_code. Follow a particular copy through the change and the two outcomes stop looking alike.

Rewind, rename, and run the same check

Don't reinsert the labels by hand. That would test your transcription, not the migration. Rewind to the savepoint and rename the existing column instead:

ROLLBACK TO trial;
ALTER TABLE score_copies RENAME COLUMN shelf_code TO location_code;
RELEASE trial;

Run the display query and the pair check again. This time the displayed labels, in ID order, are 'B-14', NULL, '', and 'B-14'. The check returns 0 missing and 0 unexpected. Notice what stayed fixed between trials: the target definition, the starting rows, and the test itself. Only the operation changed. That's why the second result tells you something the original schema comparison couldn't.

Check who still uses the old name

The values can be correct and tomorrow's checkout desk can still break. A client that asks for shelf_code by name will fail after the rename. Before choosing the deployment order, check a real read path and a real write path: the desk's lookup by copy ID, for example, and the overnight importer that files returned scores. A staff dashboard may use the new field while the importer still sends the old one.

If both clients can switch together, rehearse that switch on a disposable copy with the real indexes, views, and triggers. SQLite documents how a column rename affects dependent definitions; it cannot rewrite SQL strings in a separate application. If the clients must coexist, plan an overlap period with both names, a backfill, and a way to keep new writes consistent. Leaving two columns in place without deciding which one owns a fresh update just moves the problem to next week.

For this change, the most useful review note fits on one catalog card: copy 17 still resolves to B-14, every ID/value pair survived, and the checkout desk can read and write the new name. The schema diff supplied a question worth asking. The records and the clients supply the answer.

#sqlite#sql#migrations#schema-diff
> codebench $Ctrl+Enter Run