# Safe schema updates

> Add columns, backfill existing rows, and rename or reshape production tables safely — testing every schema update in Preview before touching Live.

- Canonical: https://exaspark.ai/docs/schema-migrations-safely/

## How schema updates move from Preview to Live

Before launch, reshaping tables in **Preview** takes seconds. Once real customers place orders or sign up in **Live**, your database becomes an active business ledger.

Clicking **Publish** promotes updated code and schema definitions to **Live** while keeping Live rows isolated from Preview test data. Every post-launch schema change must therefore respect existing Live records using the **expand and contract** pattern:

- **Expand first.** Add new tables, nullable columns, or indexes alongside existing columns so old and new code both keep working.
- **Migrate and verify.** Backfill existing rows into the new column and confirm values look right in **Cloud → Live**.
- **Contract later.** Remove obsolete columns only in a follow-up release, once live traffic runs cleanly and quick code rollbacks are no longer needed.

## Risk classification: safe vs high-risk changes

Check this table before prompting a schema edit on an app with real Live users.

| Schema change | Live risk | Why it breaks if rushed | Safe pattern |
| --- | --- | --- | --- |
| **Add a new table** | **Low** | Zero effect on existing rows | Verify in Preview, then Publish |
| **Add a nullable column** | **Low** | Existing rows stay intact with `null` | Add null-safe UI handling, verify, then Publish |
| **Add a column with a default** | **Low** | Safe if the default fits historical rows | Confirm legacy rows should inherit the default |
| **Add a non-unique index** | **Low** | Speeds queries without altering data | Add directly and verify in Preview |
| **Add `NOT NULL` without default** | **Medium** | Fails immediately on populated Live tables | Add nullable, backfill rows, then enforce `NOT NULL` |
| **Add a `UNIQUE` constraint** | **Medium** | Fails if existing rows contain duplicates | Deduplicate and normalize Live rows first |
| **Rename a column** | **High** | Drop-and-add wipes data; instant rename breaks rollback | Use the two-step expand-and-contract workflow |
| **Change a column's type** | **High** | Legacy text values (`"$25"`, `"TBD"`) fail conversion | Add new typed column, migrate, switch reads, drop old later |
| **Drop a column or table** | **High** | Erases data permanently and breaks rollback | Back up via CSV, stop referencing for one release, drop last |

## The two-step rename and type-change pattern

When renaming a populated column — or converting text prices into integer cents — split the work across two releases instead of asking for an abrupt swap.

```text
RELEASE 1 — EXPAND & BACKFILL (rollback-safe)
  1. Add `mobile_e164` (text, nullable) alongside existing `phone`.
  2. Write new updates to both `mobile_e164` and `phone`.
  3. Read `mobile_e164 ?? phone` across UI and exports.
  4. Backfill populated `phone` values into `mobile_e164` where null.
  5. Publish and verify values in Cloud (Live).

RELEASE 2 — CONTRACT (after Release 1 runs cleanly)
  1. Switch all reads and writes exclusively to `mobile_e164`.
  2. Export a safety CSV snapshot of `customers` from Cloud (Live).
  3. Drop the legacy `phone` column and Publish.
```

If Release 1 introduces an unexpected UI regression, restoring your earlier checkpoint works immediately because the original `phone` column still holds every customer's data.

### Evolving status enums without breaking old history

Adding a new enum status (like `partially_refunded`) is additive and safe — just update badges and filters to render it. Retiring an old status (replacing `processing` with `preparing`) requires backfilling every `processing` row to `preparing` **before** removing the old value from the enum.

## Backfilling existing rows and adding constraints

Whenever you introduce a field that should eventually be required — like `referral_code`, `workspace_id`, or `slug` — populate legacy rows cleanly before tightening database rules.

Good backfills follow three habits:

- **Make backfills idempotent.** Only update rows `WHERE new_column IS NULL`, so running the backfill twice produces the exact same result without overwriting values customers already edited.
- **Normalize before adding unique checks.** If you want `UNIQUE (email)` on a populated table, normalize existing emails to trimmed lowercase and resolve any duplicates first — otherwise `Alex@Acme.com` and `alex@acme.com` will cause confusing sign-in conflicts.
- **Test legacy nulls in Preview.** Before publishing, leave at least two seeded Preview rows with `null` in the new column and walk through every screen (lists, detail views, edits, CSV exports) to ensure nothing crashes on missing values.

## Step-by-step live schema release workflow

Use this repeatable five-step checklist every time a prompt alters a table that already holds real Live customer records.

1. **Export a backup of affected Live tables** — Open **Cloud → Live** (or your admin exporter) and download a CSV copy of any table you are reshaping or backfilling. See [Import & export CSV data](https://exaspark.ai/docs/csv-import-and-export/).
2. **State live-data preservation explicitly in your prompt** — Tell ExaSpark that Live already holds customer rows, specify additive columns and defaults, and forbid dropping populated fields in the same step.
3. **Verify both legacy and new rows in Preview** — In **Preview**, inspect older seeded rows (where the new column started empty) alongside newly created records across forms, dashboards, and exports.
4. **Publish and spot-check Cloud (Live)** — Click **Publish**, open **Cloud → Live**, confirm your new column and backfilled values exist, and verify existing customer counts match your pre-release snapshot.
5. **Defer destructive cleanup to a follow-up release** — Wait until the new release runs cleanly under real traffic before removing legacy columns in a separate, intentional Publish.

> **Example prompt (App):** Our Live `members` table already holds active customers, so preserve all existing Live rows with zero data loss. Add an optional `preferred_timezone` column (text, nullable) and a `loyalty_points` column (integer, default `0`, not null). Update the member profile screen to let members choose a timezone, fall back gracefully to `America/New_York` when `preferred_timezone` is null for older accounts, and seed 3 Preview members with null timezones plus 3 with explicit timezones so we can verify both cases before publishing.

## Common migration failures & recovery

If a schema change behaves oddly in Preview or triggers an error after Publish, check these five common causes first.

| What went wrong | Why it happened | How to recover safely |
| --- | --- | --- |
| **Older accounts crash on the dashboard after Publish** | New UI assumed the added column is always non-null and called `.toUpperCase()` or `.format()` on `null` | Add null-safe fallbacks in UI and API responses, backfill missing rows, and re-publish |
| **Migration fails with a `NOT NULL` violation** | Added a required column without a default value to a table that already had Live rows | Change the column to nullable (or add a sensible default), backfill legacy rows, then tighten |
| **Unique constraint fails during Publish** | Live table already holds duplicate values or inconsistent casing in that column | Inspect duplicates in **Cloud → Live**, merge or normalize conflicting rows, then apply the constraint |
| **Code rollback breaks after dropping a column** | Old checkpoint still queries a column that was deleted in the same release | Follow expand-and-contract: stop referencing the column for one full release before dropping it |
| **Enum filter hides historical orders** | Renamed an enum status in code without updating existing Live rows to the new status label | Backfill legacy rows to the updated enum label (or support both labels during transition) |

> **Note:** **Code rollbacks never rewind Live rows.** Restoring an earlier ExaSpark checkpoint reverts your app screens and routes while keeping every customer order placed since Publish safely stored in **Cloud → Live**. Keeping schema updates additive guarantees those rollbacks stay effortless.

## Next steps

- [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/) — See exactly what Publish promotes and what stays isolated in Preview.
- [Import & export CSV data](https://exaspark.ai/docs/csv-import-and-export/) — Export clean Live CSV backups before running major schema updates.
- [Staging & release hygiene](https://exaspark.ai/docs/staging-and-release-hygiene/) — Build a calm, repeatable QA and publish cadence for Live apps.

## From the blog

- [What is a database?](https://exaspark.ai/blog/what-is-a-database/) — Foundations of tables, column types, constraints, and safe data changes.
- [Why AI-built apps stall after launch](https://exaspark.ai/blog/why-ai-built-apps-stall-after-launch/) — Avoiding post-launch fragility with disciplined data and release habits.
- [App launch checklist](https://exaspark.ai/blog/app-launch-checklist/) — Essential checks for schemas, backups, and live verification before shipping.
