Database Migrations Without Losing Your Data

A migration is a saved, numbered SQL file that changes the shape of your database: add a column, rename one, add a table. The danger is that a migration can run with no error and still delete your users or make up facts about them. To avoid that, change live data in small steps, run the migration on a copy first, and test that your existing rows still mean what they meant yesterday.
Your AI tool will happily write the risky version, because the risky version is shorter. Here are four plausible migrations for “rename name to full_name and add a country column”. Each was run in a scratch project against a small Postgres holding three users (PGlite, which is Postgres compiled to run inside Node, not Supabase itself).
| Migration | What you see | What it did to your data | Safer step |
|---|---|---|---|
drop table users; then create it again | No error | All 3 users gone | Alter the table, never rebuild it |
add column country text not null default 'US' | No error | Every existing user now “lives” in the US | Add country nullable, leave old rows empty |
alter column phone type bigint | Error: invalid input syntax for type bigint: "98450 11111" | Nothing yet, but stripping non-digits to force it turns n/a into nothing | Keep phone as text |
rename column name to full_name | No error | The old app’s select name from users now fails: column "name" does not exist | Add the new column, copy, keep the old one |
The second row is the dangerous one. Nothing fails and the data is quietly wrong. Postgres is not at fault: adding a column with a plain default is fast and legal, because the default is stored once instead of written to every row (PostgreSQL docs). The problem is that “US” is a claim about people you know nothing about.
If your tool shows you SQL to approve before it runs, scan for these: drop table, truncate, a delete from with no where, a default on a not null column, a type change, a rename.
One Supabase detail makes drop table worse than data loss. A table you drop and recreate comes back with none of its row level security policies or grants, and row level security off, so it can be readable through the API until you set it up again. Why your Supabase table is public shows how to check.
What do engineers do instead?
They split a risky change into steps that are each safe. It is called expand and contract:
- Expand. Add the new column, empty (nullable, which just means “allowed to have no value”). Copy the data over. Keep the old column.
- Switch. Deploy code that uses the new column. Until the old code is gone, a trigger keeps the two columns in sync (below).
- Contract. Backfill once more, then drop the trigger and the old column in a later migration, after the longest-lived client has stopped using it. That includes a cached mobile app, not only your last deploy.
Step 1 for our example:
set lock_timeout = '5s';alter table users add column full_name text;update users set full_name = name;alter table users add column country text;
create function users_sync_full_name() returns trigger as $$begin if tg_op = 'INSERT' then new.full_name := coalesce(new.full_name, new.name); elsif new.name is distinct from old.name and new.full_name is not distinct from old.full_name then new.full_name := new.name; -- the old app changed name only end if; return new;end $$ language plpgsql;
create trigger users_sync before insert or update on users for each row execute function users_sync_full_name();The copy runs once, but the old app keeps running after it. Without the trigger, a user who signs up through the old app between the migration and the switch has an empty full_name, and the contract step then drops the only copy of their name. Right before the contract step, run update users set full_name = name where full_name is null as a final check, then drop the trigger, the function and name.
country stays empty for old users because we do not know it. Empty is honest. You can add not null later, once every row has a real value. Postgres normally scans the whole table to check and blocks other updates meanwhile; adding a check (country is not null) constraint as not valid first, then validate constraint, shortens that lock, and a valid check constraint lets set not null skip the scan (PostgreSQL docs).
Two details engineers add that AI tools skip. lock_timeout makes the migration give up if it cannot get its lock in 5 seconds, instead of queuing behind a slow query while every other query queues behind it. Postgres documents it as a timeout that only fires while waiting for locks (PostgreSQL docs). And on a big table, copy the data in batches (update ... where id >= 1 and id < 10001, then the next range) so no single transaction holds rows for long. In a scratch run with 200,000 rows, one update took about 0.7 seconds and 20 batches took about the same. Batching does not make it faster. It keeps each transaction short, which is what lets other users’ queries in. That effect was not measured, since the scratch database had one user.
What does it look like on Supabase?
Write the migration as a file, test it locally, then apply it: supabase migration new, supabase db reset (rebuilds your local database from all migrations and seed.sql, and wipes local data), then supabase db push (Supabase docs). The same page warns that editing your remote database in the SQL editor “bypasses the migration history and will cause db push to fail with sync errors.” If you have already done that, run supabase db pull first: it writes the remote schema into supabase/migrations so the history matches again (CLI reference).
Prove it with a test
The test builds “production as it is today”, with Asha, Ben and Chen in it, runs the migration, and asks what they still have. It checks meaning, not SQL, so any later change that damages them fails it. Test 2 encodes a choice: we prefer an empty country to a guess. Tests 4 and 5 cover the old app writing while the switch is in progress. The setup is a scratch project: npm i @electric-sql/pglite, "type": "module" in package.json, node --test, with the migration SQL exported from migration.js as export const migration. Not an engineer? Skip to the prompt below.
import { test } from 'node:test'import assert from 'node:assert/strict'import { PGlite } from '@electric-sql/pglite'import { migration } from './migration.js'
// The database as it is in production today: real users already exist.async function productionToday() { const db = new PGlite() await db.exec(` create table users (id serial primary key, name text, phone text); insert into users (name, phone) values ('Asha', '98450 11111'), ('Ben', 'n/a'), ('Chen', '+1 415 555 0100'); `) return db}
test('every existing user survives with the same id, name and phone', async () => { const db = await productionToday() await db.exec(migration) const { rows } = await db.query('select id, full_name, phone from users order by id') assert.deepEqual(rows, [ { id: 1, full_name: 'Asha', phone: '98450 11111' }, { id: 2, full_name: 'Ben', phone: 'n/a' }, { id: 3, full_name: 'Chen', phone: '+1 415 555 0100' }, ])})
test('we do not invent a country for people who never gave one', async () => { const db = await productionToday() await db.exec(migration) const { rows } = await db.query('select country from users') assert.equal(rows.length, 3) assert.ok(rows.every((r) => r.country === null), 'old users were given a made-up country')})
test('the old app, still running, can read names', async () => { const db = await productionToday() await db.exec(migration) const { rows } = await db.query('select name from users order by id') assert.deepEqual(rows.map((r) => r.name), ['Asha', 'Ben', 'Chen'])})
test('a user who signs up through the old app after the migration still has a full name', async () => { const db = await productionToday() await db.exec(migration) await db.exec("insert into users (name, phone) values ('Dana', '555 0101')") // the old app knows only `name` const { rows } = await db.query("select full_name from users where name = 'Dana'") assert.equal(rows[0].full_name, 'Dana')})
test('a name the old app edits after the migration reaches full_name too', async () => { const db = await productionToday() await db.exec(migration) await db.exec("update users set name = 'Asha K' where id = 1") const { rows } = await db.query('select full_name from users where id = 1') assert.equal(rows[0].full_name, 'Asha K')})Run the drop-and-recreate migration and the first three tests fail. Run rename plus default 'US' and test 1 passes while 2 and 3 fail:
ok 1 - every existing user survives with the same id, name and phonenot ok 2 - we do not invent a country for people who never gave onenot ok 3 - the old app, still running, can read namesRun the expand step without the trigger (the first four lines of the SQL above) and tests 1 to 3 pass while tests 4 and 5 fail, which is the data loss described earlier:
ok 3 - the old app, still running, can read namesnot ok 4 - a user who signs up through the old app after the migration still has a full namenot ok 5 - a name the old app edits after the migration reaches full_name tooRun the full expand step with the trigger and all five pass. These tests run on three rows, so they prove correctness, not speed or locking. PGlite also cannot see your row level security policies or role grants, and a recreated table can lose those, so a real check needs your real database. Nothing here was run on a hosted Supabase project: the supabase db push, db dump --remote and migration history behavior come from the CLI docs, not from a live run.
A prompt to start with
I need to change my database: [describe it]. Do not write the migration yet. List what it could damage in existing rows: dropped columns, defaults that guess a value, type changes that fail or lose information, renames that break the running app. Then write it as small steps that keep the old column until the app stops using it. First write a test that seeds realistic existing rows, runs the migration, and checks every old row survives with the same meaning and no value is invented. Show it failing on the naive version, then passing on yours.
The one check an engineer does by hand
Before production, dump the schema of production (supabase db dump --remote, see the CLI reference; without --remote it dumps your local database), load it into a scratch database such as a second free project or your local one, fill it with fake rows that look like yours, and run the migration there. Copying real user data down puts it somewhere with weaker protection, as staging vs production explains; if you truly need real rows, use a scrubbed copy on your own machine and delete it afterwards. Check the row count, a few rows you know by heart, and your busiest page. The Supabase CLI docs do not describe a one-command way to undo a migration on production, so plan on a new migration that fixes forward, or a restore from backup. The code side is covered in rolling back a bad deploy.
This sits next to staging vs production. It is also part of the launch checklist.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.