Databases: choosing data types, primary keys, NULL and schema changes before the table gets big
Why an INT id, FLOAT money, utf8 strings or a UUID v4 primary key, picked in five minutes, cost a whole night to fix once the table has billions of rows. Data types, primary keys, NULL, the SQL command groups and safe schema changes on MySQL 8.4 and PostgreSQL, plus how to review AI-written migrations.
On this page
1. The problem
A shop has run for 5 years with orders.id INT. On a sale night the id hits 2,147,483,647 and every new INSERT fails with a duplicate key. Moving to BIGINT means copying a 300 GB table and blocking writes for hours.
2. Key idea
Types and keys decide how data sits on disk; changing them rewrites every row and every index. Each column is a promise about its domain, maximum growth and comparison rules. Promise tightly from the start (NOT NULL, CHECK, wide-enough types): loosening is cheaper than tightening.
| Wrong choice | Symptom | Root cause |
|---|---|---|
id INT |
INSERTs fail at 2,147,483,647 | signed INT is only 4 bytes |
Money as FLOAT/DOUBLE |
reconciliation off by a few cents | 0.1 + 0.2 ≠ 0.3 in binary |
Charset utf8 |
emoji fail with Incorrect string value |
MySQL's utf8 is utf8mb3, 3 bytes per character |
| UUID v4 primary key | INSERTs slow down, indexes bloat | writes land randomly in the B+tree |
| Nullable columns | <>, NOT IN lose rows |
comparing with NULL gives UNKNOWN |
| Choice | Use when | Don't use when |
|---|---|---|
BIGINT ids |
the table may grow, or you're unsure | small lookup tables |
DECIMAL(p, s) |
money, quantities that must be exact | measurements that tolerate error |
Surrogate PK + UNIQUE natural key |
most business tables | N–M junction tables (composite PK) |
UUID v7 stored as BINARY(16) |
ids generated in many places, or exposed in URLs | one database, internal ids |
| Nullable | "unknown" really differs from "none" | there's a sensible default: NOT NULL DEFAULT |
3. In SQL
-- MySQL 8.4 LTS, InnoDB (session time_zone = '+00:00' to store UTC)
CREATE TABLE orders (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
public_id BINARY(16) NOT NULL UNIQUE, -- UUID v7 generated by the app
total DECIMAL(12,2) NOT NULL CHECK (total >= 0),
status VARCHAR(20) NOT NULL DEFAULT 'NEW',
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
) DEFAULT CHARSET = utf8mb4;
-- PostgreSQL 18 and later
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- instead of SERIAL
public_id uuid NOT NULL UNIQUE DEFAULT uuidv7(),
total numeric(12,2) NOT NULL CHECK (total >= 0),
created_at timestamptz NOT NULL DEFAULT now()
);Other languages: JPA @GeneratedValue(strategy = IDENTITY) disables batch inserts, so prefer SEQUENCE on PostgreSQL; Node's pg returns numeric as strings.
ALTER on big tables and expand/contract
- MySQL 8.4 runs
ALTERwith three algorithms: INSTANT (metadata only, e.g. adding a column), INPLACE (rebuilds indexes, allows concurrent writes), COPY (copies the table, blocks writes; e.g. changing a column type). WriteALGORITHM=INSTANTso MySQL errors instead of silently copying. - Every
ALTER, even INSTANT, needs an exclusive metadata lock for a moment. A long open transaction on the table makes theALTERwait, and every later statement queues behind it. - Very large tables: gh-ost or pt-online-schema-change build a shadow table and swap names.
- Expand/contract for renames: add the new column, write both, backfill in batches, read the new one, drop the old one last. Never in a single deploy.
- PostgreSQL: create indexes on big tables with
CREATE INDEX CONCURRENTLY.
4. Working with AI
Hand to AI: draft Flyway migrations, sample data with edge cases (NULLs, emoji, fractional amounts), looking up ALTER algorithms by version (then check the docs).
Check yourself in AI-written code:
- Ids of tables that may grow are
BIGINT, including every foreign key pointing at them. - Money is
DECIMAL/numeric; the charset isutf8mb4. - Every nullable column has a reason; queries on it don't use
<>/NOT INforgetting NULL. -
ALTERs on big tables stateALGORITHMand set a shortlock_wait_timeout. - Renames and drops follow expand/contract, not the same deploy as the new code.
5. Exercises
Exercise 1: Review "customers who haven't verified their email"
The email_verified TINYINT NULL column was added two years ago; 18,000 old accounts are NULL. The AI wrote the query below and says "simple, works". The reminder email reaches 2,400 people instead of 20,400. Find the bug, give proof data, fix it.
SELECT id, email FROM account WHERE email_verified <> 1;Solution 1
NULL <> 1is UNKNOWN, andWHEREkeeps only TRUE rows: 18,000 rows drop out.- Data: three rows with
email_verified1, 0, NULL. Expected 2 rows; actual 1. - Fix the query:
WHERE email_verified = 0 OR email_verified IS NULL; MySQL shorthandWHERE NOT (email_verified <=> 1), PostgreSQLIS DISTINCT FROM 1. - Fix the root: NULL here means "not verified". Backfill to 0 in batches and make the column
NOT NULL DEFAULT 0.
Exercise 2: Read an incident
At 14:02 someone runs ALTER TABLE orders ADD COLUMN note VARCHAR(255) NULL, ALGORITHM=INSTANT;. By 14:06, API p99 goes from 80 ms to 30 seconds and the connection pool is exhausted. SHOW PROCESSLIST: the ALTER is in Waiting for table metadata lock, with 212 statements waiting behind it. innodb_trx shows a transaction open since 13:24, sleeping. Diagnose it, say what to do in 15 minutes, fix the root cause.
Solution 2
- Diagnosis: INSTANT still needs an exclusive metadata lock. The 13:24 transaction holds a shared MDL on
orders, theALTERwaits, and every new statement queues behind theALTER. - 15 minutes:
KILLtheALTERso the queue drains; find the 13:24 session viatrx_mysql_thread_idandKILLit if abandoned. Rerun withSET SESSION lock_wait_timeout = 5;. - Root fix: find what opens long transactions (report jobs,
@Transactionalmethods making HTTP calls). The migration pipeline checksinnodb_trxfirst and sets a shortlock_wait_timeoutby default.
Summary
- Money
DECIMAL, idsBIGINT, stringsutf8mb4, instants in UTC. - InnoDB PKs short and increasing; UUIDs means v7.
- NULL means "unknown":
<>andNOT INdrop NULL rows. - Every
ALTERneeds a metadata lock; set a shortlock_wait_timeout. - Schema changes during rolling deploys: expand/contract through migrations.
Further reading: ERDs, JOIN, GROUP BY.
Practice interview questions on this topic
- What are DDL, DML, DCL and TCL? How do DELETE, TRUNCATE and DROP differ?
- What are the NULL pitfalls in SQL, and why can NOT IN return nothing?
- How does a primary key differ from a unique key, and a key from an index?
- Auto-increment, UUIDv4 or UUIDv7/ULID as primary key, and why does UUIDv4 slow InnoDB down?
All SQL & Query Tuning questions →All Data Modeling & Scaling questions →
Comments
Community rules