Sub topic 3
Adding a column
This chapter covers ALTER TABLE ... ADD COLUMN. It assumes you can write CREATE TABLE with common data types, understand primary and foreign keys, and have a test database such as PostgreSQL, MySQL, SQL Server or SQLite. Run every example on a test database, not on data you care about.
The basic statement
Adding a column is the most common structural change. Applications grow new features, and those features need somewhere to store new facts. The statement has three parts: the table, the keyword ADD COLUMN, and a column definition written the same way as in CREATE TABLE.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
ALTER TABLE customers ADD COLUMN email VARCHAR(255);The new column is added at the end of the table. Every row that already exists gets NULL in it, because you did not say what else to store. Adding a nullable column with no default is the safest form of the change. No existing row is invalid afterward, and no existing query or INSERT breaks.
You can check the result with ordinary SQL:
INSERT INTO customers (id, name) VALUES (1, 'Ada');
SELECT id, name, email FROM customers;The row for Ada shows NULL under email. An INSERT that lists its columns, as the one above does, keeps working after the change. An INSERT that omits the column list now fails because it supplies one value too few. This is one reason to always name columns in INSERT statements.
What happens to existing rows
The database must give every existing row a value for the new column. That value comes from one of two places:
- Without a
DEFAULT, the value isNULL. - With a
DEFAULT, the value is the default.
The second case matters most when the column is NOT NULL:
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';Existing rows receive 'active', so the NOT NULL rule holds from the first moment. The default also applies to future inserts that leave status out.
If you leave out the default on a NOT NULL column, the result depends on whether the table has rows:
ALTER TABLE customers ADD COLUMN country CHAR(2) NOT NULL;On an empty table this succeeds. On a table with rows, PostgreSQL and SQLite refuse it with an error, because the existing rows would have to contain NULL. Some systems or modes behave differently. MySQL, for example, may fill in an implicit default for the type, such as an empty string. Do not rely on that. State the default you mean.
The three-step pattern
Sometimes old rows need different values, and no single default fits. For example, you might want to fill country from data held somewhere else. In that case use three steps. This sketch uses PostgreSQL syntax for the last step:
ALTER TABLE customers ADD COLUMN country CHAR(2);
UPDATE customers SET country = 'GB' WHERE country IS NULL;
ALTER TABLE customers ALTER COLUMN country SET NOT NULL;The final step fails if any NULL is left, which makes it a useful check. Later chapters cover SET NOT NULL and its other-dialect equivalents in detail.
Defaults can be expressions
A default is not limited to literals. Most databases accept functions such as the current timestamp:
ALTER TABLE customers
ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;Existing rows get the time at which the ALTER TABLE ran, not their true creation time. That is a data-quality point as well as a syntax point. A column named created_at that holds a made-up value for old rows can mislead anyone who reads it later. If the true value is unknown, prefer a nullable column and let NULL mean "unknown".
Adding several columns
Standard SQL allows one ADD per clause, and PostgreSQL and MySQL let you chain several clauses with commas in a single statement:
ALTER TABLE customers
ADD COLUMN phone VARCHAR(30),
ADD COLUMN birth_date DATE;One statement is usually better than two. The database can often do the work in one pass over the table, and the change applies as a single unit. SQL Server and Oracle use a different shape. SQL Server writes ADD phone VARCHAR(30), birth_date DATE with no COLUMN keyword and no repeated ADD. Oracle writes ADD (phone VARCHAR2(30), birth_date DATE) with parentheses.
Dialect differences that affect `ADD COLUMN`
| Feature | PostgreSQL | MySQL | SQL Server | SQLite |
|---|---|---|---|---|
| `COLUMN` keyword | Optional | Optional | Not allowed | Optional |
| `IF NOT EXISTS` | Supported | Not in MySQL (MariaDB supports it) | Not supported | Not supported |
| Choose position | No, always last | `FIRST` or `AFTER col` | No, always last | No, always last |
| Several columns in one statement | Yes | Yes | Yes, with one `ADD` | No, one column per statement |
Two points deserve attention.
IF NOT EXISTS. In PostgreSQL,ALTER TABLE customers ADD COLUMN IF NOT EXISTS email VARCHAR(255);makes a script safe to re-run. In databases without the clause, a second run fails with a "duplicate column" error. You then need to check the system catalog first, or use a migration tool that records which changes it has already applied.- Column position. MySQL lets you write
ADD COLUMN email VARCHAR(255) AFTER name. In other systems the new column always lands at the end. Position should not matter to well-written code, because queries should name their columns. If you depend on column order, for example withSELECT *, your code is fragile in any dialect.
SQLite has extra limits. A NOT NULL column must have a non-NULL default. You cannot add a PRIMARY KEY or UNIQUE column this way. Defaults must be constants rather than expressions such as CURRENT_TIMESTAMP. For those cases SQLite needs you to create a new table and copy the data across.
Cost on large tables
How long the statement takes depends on the database and on what you ask for.
- Many modern engines add a column that is nullable, or has a constant default, as a change to the table's metadata only. They do not rewrite the stored rows. PostgreSQL 11 and later does this for constant defaults, and MySQL 8.0.12 and later can often add a column instantly.
- A default that has to be computed for each row can force a full rewrite of the table. In PostgreSQL, a volatile default such as
random()does this. A rewrite takes time in proportion to table size, and it usually holds a strong lock that blocks other sessions.
Even a quick metadata change needs a brief lock on the table. If a long-running transaction already holds a lock on it, your ALTER TABLE waits, and every query that arrives after it can queue behind it. Later chapters cover locking in more detail. For now, test the statement on a copy of realistic size before you run it in production.
Common mistakes
- Adding
NOT NULLwithout a default to a table that has rows, then seeing the statement fail. - Using
CURRENT_TIMESTAMPas a default and treating the resulting values as real history. - Writing
ADD COLUMNon SQL Server, which does not accept theCOLUMNkeyword here. - Relying on column position, or on
SELECT *, after the table changes. - Re-running a script that already added the column, without
IF NOT EXISTSor a migration record.
Exercises
Exercise
A table named invoices has 40,000 rows. You run ALTER TABLE invoices ADD COLUMN currency CHAR(3) NOT NULL; and PostgreSQL returns an error. Why, and how do you write a version that works if every existing invoice should use 'USD'?
Show answer
The existing 40,000 rows would have to hold NULL in a NOT NULL column, so the database rejects the change. Supply a default: ALTER TABLE invoices ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD'; Existing rows receive 'USD' and the rule holds immediately.
Exercise
Existing customers have no known signup date. You add signupdate DATE NOT NULL DEFAULT CURRENTDATE. What is wrong with the data this produces, and what would you do instead?
Show answer
Every existing customer gets the date on which the ALTER TABLE ran, which is false history that looks like real data. Add signup_date as a nullable DATE with no default, so old rows hold NULL meaning "unknown". Backfill real dates if a source exists, and add NOT NULL only afterward if it is still appropriate.