# Renaming a Database Column Without Downtime

My earlier [posts](https://zyvop.com/setting-up-ci-cd-for-zyvop-com-with-github-actions-test-build-tag-deploy-roll-back-r8vrp) kept saying "expand and contract" without ever showing it end to end. This one does. I'll rename `users.fullname` to `users.display_name` on a live PostgreSQL database, one safe step at a time. The sequence works on any database, but the SQL and locking details below are PostgreSQL.

**TL;DR:** never rename in one step. Add the new column, dual-write, backfill in batches, verify, switch reads, stop writing the old column, and only then drop it. Put a `lock_timeout` on every DDL statement.

* * *

## Why a plain rename breaks

```sql
ALTER TABLE users RENAME COLUMN fullname TO display_name;
```

It runs instantly, and it still causes an outage, for three reasons:

1.  **Running code breaks immediately.** During a rolling deploy, old and new versions run side by side. Anything still saying `fullname` (old servers, workers, cron jobs, scripts) starts failing the moment the rename lands.
    
2.  **It needs an** `ACCESS EXCLUSIVE` **lock**, which conflicts with everything, including plain `SELECT`. If a long query is holding the table, the `ALTER` waits, and every query that arrives after it queues behind it. A "fast" statement can stall the whole table.
    
3.  **Rolling back the code doesn't un-rename the column.**
    

Many ORMs' rename helpers just run that one statement, so I don't use them on a live table.

* * *

## The plan

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpVkWFP2zAQhv_KcZ-dbAzYpGpjIi0IJOBDqhVNMZou8aW1cOzIdhe6qv99ioMq-OhXz-P3fN5j4xTjDFvjhmZDPsJ9KS0AwHUl8TSH69eerPpe-0-XpBQoHXpDuz-WOpb4DFl2CYtK4pccFlsy2eB15ER7NkyB4Uri83TjItFFJfEsh4Kal1Ybk1hnFHg3BAHaQk2x2XA4akXSVnuJ5zms2Ot2l6ROh25C4Qd8_inxMPEryDJ4dFPZu-g3h5SVlcSLHEomBZaHD8MWx9YysU-VxK85LKPrYXyatmtwRn1w5kfnKTnzSuK3HObORk9NTKzyrod2a8zb3lBgx74jrXC2x7jhbvwExS1tTUQxJSvymmrDYWRaZ-MNddrscIYZ9b3hLOxC5E5AYbR9eaBmmc43zkYBEpe8dgy_7iQKKF3tohNwy-YvR92QgCuvyQgIZEMWxq2iSCVL_W-c5fS8f8XDQWC9njvjPM7wZNjoyHj4D4BDsWE?type=png)

| Step | What ships | App writes | App reads | Roll back the app? |
| --- | --- | --- | --- | --- |
| 1. Expand | Migration: add display_name | fullname | fullname | Yes |
| 2. Dual-write | Release A | both | fullname | Yes |
| 3. Backfill | Data migration, in batches | both | fullname | Yes |
| 4. Verify | One query | both | fullname | Yes |
| 5. Read new | Release B | both | display_name | Yes |
| 6. Stop writing old | Release C | display_name | display_name | To B yes, to A no (it would read a stale fullname) |
| 7. Contract | Migration: drop fullname | display_name | display_name | No. Point of no return |

**The rule:** ship each step only after the previous one is fully deployed everywhere, including background workers, cron jobs, and one-off scripts.

* * *

## Step 1: Expand

```sql
SET lock_timeout = '3s';
ALTER TABLE users ADD COLUMN display_name text;
```

-   Adding a nullable column with no default doesn't rewrite the table.
    
-   `lock_timeout` is the important line. If the lock isn't available within 3 seconds, the statement fails instead of joining the queue and blocking everyone behind it. I wait a few seconds and run it again.
    
-   If my migration tool wraps migrations in a transaction, I use `SET LOCAL lock_timeout` so the setting doesn't leak.
    
-   This ships as its own migration step, before the app code that uses the column.
    

If the old column has an index, create the equivalent on the new one now:

```sql
CREATE INDEX CONCURRENTLY users_display_name_idx ON users (display_name);
```

`CONCURRENTLY` avoids blocking writes, but it can't run inside a transaction block, so my migration tool has to run it without one. If it fails partway, it leaves an `INVALID` index behind. I drop that index and try again.

* * *

## Step 2: Dual-write (release A)

Every write sets both columns:

```javascript
await db.query(
  "UPDATE users SET fullname = $1, display_name = $1 WHERE id = $2",
  [name, id]
);
```

Inserts set both too. Reads still use `fullname`. I route every write through one shared function so no code path is missed: app code, workers, admin scripts, import jobs. If I can't guarantee every writer is updated, a database trigger that keeps the two columns in sync is the safety net, but it's more moving parts, so I only use one when I have to.

* * *

## Step 3: Backfill

```sql
UPDATE users
SET display_name = fullname
WHERE id IN (
  SELECT id FROM users
  WHERE display_name IS NULL AND fullname IS NOT NULL
  ORDER BY id
  LIMIT 5000
);
```

A small script runs this repeatedly, with a short pause between batches, until it reports zero rows updated.

-   **Batches matter.** One giant `UPDATE` holds locks for a long time, bloats the table (every updated row becomes a new row version), and can make replicas lag.
    
-   `fullname IS NOT NULL` **is not optional.** A row whose `fullname` is `NULL` would match `display_name IS NULL` forever, the update would never change it, and the loop would never finish.
    
-   **It's safe alongside dual-write.** It only touches rows the app hasn't already filled.
    

* * *

## Step 4: Verify

```sql
SELECT count(*) FROM users WHERE display_name IS DISTINCT FROM fullname;
```

This must return `0`. `IS DISTINCT FROM` treats `NULL` as a comparable value, so two NULLs count as equal. A plain `<>` would skip any row where either side is `NULL` (because `NULL <> 'x'` is `NULL`, not true), so it would report zero mismatches even when rows are missing. The query scans the table, so I run it off-peak.

* * *

## Step 5: Read the new column (release B)

Release B reads `display_name` and keeps dual-writing. Every row now has a value and every writer keeps it current, so reads are correct. Because it still writes `fullname`, rolling back to release A is safe.

* * *

## Step 6: Stop writing the old column (release C)

Release C writes only `display_name`. From here, `fullname` goes stale, which is why rolling back to A is no longer safe.

I wait at least one full release cycle here. Before moving on, I search the codebase for `fullname`, and check the database's query statistics (`pg_stat_statements`, if enabled) for any query still touching it. Reports, dashboards, and exports are the usual stragglers.

* * *

## Step 7: Contract

```sql
SET lock_timeout = '3s';
ALTER TABLE users DROP COLUMN fullname;
```

-   It ships as a separate, later migration.
    
-   It's quick. PostgreSQL just makes the column invisible, and the disk space is reclaimed gradually.
    
-   The default is `RESTRICT`, so it fails if a view or other object still depends on the column. I fix the dependency instead of reaching for `CASCADE`.
    
-   It's the point of no return. Code that still needs `fullname` will break, and getting the data back means restoring a backup.
    

* * *

## What else knows the old name

| Thing | What I do |
| --- | --- |
| Indexes and unique constraints | Create equivalents on the new column before step 5 |
| NOT NULL | Backfill first, then ADD CONSTRAINT ... CHECK (display_name IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, then SET NOT NULL. PostgreSQL skips the full scan when a valid CHECK already proves there are no NULLs. I drop the CHECK in a separate statement afterwards. Each statement takes a brief lock, so lock_timeout applies to every one. |
| Views, functions, triggers | Update them before the contract step |
| API responses and clients | A column rename doesn't have to change an API field. I keep the API stable or version it. |
| Reports, ETL, BI dashboards | Search for them and warn their owners |

* * *

## Checklist

-   Rehearsed the whole sequence on a copy of production data
    
-   `lock_timeout` set on every DDL statement, with a retry plan
    
-   Expand migration ships before the code that uses the new column
    
-   Every writer dual-writes: app, workers, scripts, imports
    
-   Backfill runs in batches with `fullname IS NOT NULL`, until 0 rows updated
    
-   Verification query returns 0 using `IS DISTINCT FROM`
    
-   Each step is fully deployed before the next one ships
    
-   Contract is a separate migration, after a quiet period
    
-   Indexes, constraints, views, functions, API, and reports checked
    

* * *

## Final thoughts

The rename itself is one line of SQL. The safe version is seven small, boring steps, and that's the point: at every step, both the current release and the previous one work, so a deploy never needs the database to change at the same instant as the code.

_Have you been bitten by a rename or migration on a live database? Tell me in the comments and I'll cover it in a follow-up._

---

*Published via [ZyVOP](https://zyvop.com/renaming-a-database-column-without-downtime-h9r5k?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
