Adding a new column is one of the most common schema changes in any database. It sounds simple but a poor approach can lock tables, slow queries, or cause downtime in production. The right steps are precise, safe, and predictable.
In modern SQL databases like PostgreSQL, MySQL, and MariaDB, the basic syntax is direct:
ALTER TABLE users ADD COLUMN last_login TIMESTAMP;
This works, but large datasets demand more care. On massive tables, a naive ALTER TABLE can block reads and writes. Production-grade deployments often use one of these strategies:
- Online schema change tools like pt-online-schema-change or gh-ost.
- Rolling changes with feature flags to handle nulls before writes.
- Default values managed in application code instead of
ALTER TABLEdefaults.
When creating a new column, always define the data type for its future workload. A wrong type leads to wasted storage or broken queries. Adding indexes at the same time can compound locking issues; it’s better to create the column first, backfill the data, then add the index in a later migration.