SteelReed

Search

Search posts, questions…

4. Database & SQL

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.

17 Nov 20268 min readJunior

–

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

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 ALTER with 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). Write ALGORITHM=INSTANT so 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 the ALTER wait, 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 is utf8mb4.
  • Every nullable column has a reason; queries on it don't use <>/NOT IN forgetting NULL.
  • ALTERs on big tables state ALGORITHM and set a short lock_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.

SQL
SELECT id, email FROM account WHERE email_verified <> 1;
Solution 1
  • NULL <> 1 is UNKNOWN, and WHERE keeps only TRUE rows: 18,000 rows drop out.
  • Data: three rows with email_verified 1, 0, NULL. Expected 2 rows; actual 1.
  • Fix the query: WHERE email_verified = 0 OR email_verified IS NULL; MySQL shorthand WHERE NOT (email_verified <=> 1), PostgreSQL IS 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, the ALTER waits, and every new statement queues behind the ALTER.
  • 15 minutes: KILL the ALTER so the queue drains; find the 13:24 session via trx_mysql_thread_id and KILL it if abandoned. Rerun with SET SESSION lock_wait_timeout = 5;.
  • Root fix: find what opens long transactions (report jobs, @Transactional methods making HTTP calls). The migration pipeline checks innodb_trx first and sets a short lock_wait_timeout by default.

Summary

  • Money DECIMAL, ids BIGINT, strings utf8mb4, instants in UTC.
  • InnoDB PKs short and increasing; UUIDs means v7.
  • NULL means "unknown": <> and NOT IN drop NULL rows.
  • Every ALTER needs a metadata lock; set a short lock_wait_timeout.
  • Schema changes during rolling deploys: expand/contract through migrations.

Further reading: ERDs, JOIN, GROUP BY.

Practice interview questions on this topic

All SQL & Query Tuning questions →All Data Modeling & Scaling questions →

Loading comments…