Evolving a schema: JSON columns, online DDL, data types and views
Why spare columns c1..c6 are obsolete, adding columns and indexes without downtime on MySQL 8.4/9.7 and PostgreSQL 18, indexing JSON fields (and why PostgreSQL 18's VIRTUAL generated columns can't be indexed), choosing string, number, money and time types, MERGE, TEMPTABLE and materialized views with their performance and security traps, real measurements, and how to review migrations an AI wrote.
On this page
1. The problem
A migration adding a nullable column to orders took 3 ms in rehearsal. In production it queued behind a 10-minute report; every new SELECT queued behind it, and the API returned 503 for 10 minutes. The ALTER wasn't wrong; it just lacked a lock_timeout line.
2. Key idea
Data outlives code, so schema changes on big tables follow expand/contract: add the new column, dual-write, backfill in batches, switch reads, and only then drop the old column.
| Choice | Use when | Don't use when |
|---|---|---|
| Real column | filtering, JOINs, sorting, NOT NULL, CHECK, FKs |
attributes vary by record type |
| JSON | sparse, varies by record type, display only | the field appears in every WHERE |
| Expression index / GIN on JSON | occasional filtering on one JSON field | it's become a main condition: promote it to a column |
| View | simplifying queries, backward compatibility after a rename | hiding a GROUP BY and then joining to it |
2.1 What does an "online" ALTER lock?
Adding a nullable column now only touches metadata (MySQL INSTANT, PostgreSQL 11+). But the start and end of every ALTER still need a brief exclusive lock. If a long transaction is reading the table, the ALTER waits for it, and every new query queues behind the ALTER.
Two things still rewrite the whole table: ADD COLUMN with a volatile default (now() on old MySQL, gen_random_uuid()), and changing a column's type. Money uses DECIMAL or integers because FLOAT is base 2 and drifts by 0.01.
3. In SQL
Every migration: wait at most a few seconds for locks, then fail so the tool can retry.
SET lock_timeout = '3s'; -- PostgreSQL
-- SET SESSION lock_wait_timeout = 3; -- MySQL
ALTER TABLE orders ADD COLUMN note text; -- metadata only, a few ms
-- Doesn't block writes; can't run inside a transaction: a separate migration
CREATE INDEX CONCURRENTLY orders_note_idx ON orders (note);
-- Index one JSON field without adding a column
CREATE INDEX CONCURRENTLY app_user_referral_idx ON app_user ((data->>'referral_code'));
-- PostgreSQL 18: NOT NULL without a long lock, validated afterwards
ALTER TABLE orders ADD CONSTRAINT note_nn NOT NULL note NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT note_nn;Flyway, Liquibase, golang-migrate and Prisma all hit exactly these locks, because it's the database's doing.
Data types and views: traps worth remembering
- Integers: the smallest type that fits; ids that may grow should be
BIGINTfrom the start.INT(11)is only a display width. - MySQL time:
TIMESTAMPstores UTC, converts with the sessiontime_zone, and ends in 2038;DATETIMEdoesn't convert. PostgreSQL usestimestamptz. - NULL: avoid it when a meaningful default exists, but don't invent fake values (
'1970-01-01',-1). - MERGE vs TEMPTABLE views (MySQL): views with
GROUP BY,DISTINCT,LIMITorUNIONare computed into a temp table first. Joining 3 authors to a post-count view over 2 million posts can aggregate almost the whole table; aCROSS JOIN LATERALcounts each author through an index. - Permissions: PostgreSQL views run with the view owner's rights by default; set
security_invoker = true(PostgreSQL 15+) so row-level security applies to the caller. - Generated columns on PostgreSQL 18 are virtual by default and can't be indexed; write
STORED(which rewrites the table) or use an expression index.
4. Working with AI
Hand to AI: drafting expand/contract migrations, batch backfill scripts, listing views with GROUP BY that get joined.
Check in AI-written code:
- Every migration sets a
lock_timeoutof about 3 seconds. - No
ADD COLUMNwith a volatile default on large tables. - PostgreSQL indexes use
CONCURRENTLY, outside a transaction. - No
FLOAT/DOUBLEfor money. - Renames and type changes go through expand/contract, not one
RENAME.
5. Exercises
Exercise 1: Review an "online" migration
The AI generated a PostgreSQL 18 migration for a 50-million-row app_user table, calling it "online, no downtime, runs in a few ms". Find three bugs, show how to prove them, fix them.
ALTER TABLE app_user ADD COLUMN public_id uuid NOT NULL DEFAULT uuidv7();
ALTER TABLE app_user ADD COLUMN referral_code text GENERATED ALWAYS AS (data->>'referral_code');
CREATE INDEX app_user_referral_idx ON app_user (referral_code);Solution to Exercise 1
DEFAULT uuidv7()is volatile: PostgreSQL rewrites the whole table underACCESS EXCLUSIVE(1 million rows already took about a second; 50 million freezes the table for a minute or more). Fix: add a nullable column, set the default for new rows, backfill in batches, thenNOT NULL ... NOT VALIDandVALIDATE.- The generated column isn't
STORED, so it's virtual; the followingCREATE INDEXfails withindexes on virtual generated columns are not supported. Fix: drop the generated column and use an expression index((data->>'referral_code')). CREATE INDEXwithoutCONCURRENTLYblocks writes for the whole build; the file also lacksSET lock_timeout.
Proof: run each statement on a 1-million-row copy with \timing, and watch pg_locks from another session to see the locks held.
Exercise 2: Read a post-migration 503 incident
At 14:00 Flyway runs ALTER TABLE orders ADD COLUMN note text. From 14:00 to 14:10 the API returns 503 and pg_stat_activity is full of wait_event = relation on orders. A report job started at 13:58 is state = active, reading orders. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the
ALTERneeds a brief exclusive lock but waits behind the report (holding a shared lock). Every new query queues behind theALTER: the whole table stalls although the statement needs only milliseconds. - 15 minutes: cancel the
ALTERsession (pg_cancel_backend); queries resume at once. Rerun the migration after the job finishes. - Root fix:
SET lock_timeout = '3s'at the top of every migration so theALTERgives up instead of freezing the table, with retries; run long reports on a replica; setstatement_timeoutfor report sessions.
Summary
- Real columns for what you filter, join or constrain; JSON for sparse, display-only attributes.
- Adding a column is nearly instant now; the brief locks at start and end can still freeze a table.
- Every migration sets
lock_timeout; indexes useCONCURRENTLY. - Money uses
DECIMALor integers. - Joining a view with
GROUP BYcomputes the whole view.
Read more: Part 3: Case studies: translations, ordering, calendars and reports.
Practice interview questions on this topic
- How do views and materialized views differ, and what should you watch when using views for access control?
- How do you choose column types: money, INT(11), VARCHAR or TEXT?
- When should an attribute go into a JSON column, and when into real columns or tables?
- Why can an "online" ALTER still stall production, and how do you migrate schemas safely?
- How should you store points in time: TIMESTAMP, DATETIME or timestamptz?
All SQL & Query Tuning questions →All Data Modeling & Scaling questions →
Comments
Community rules