Sub topic 3
Adding a Column with `ALTER TABLE`
Assume you know basic CREATE TABLE, SELECT, INSERT, and common constraints such as PRIMARY KEY and NOT NULL. This chapter uses PostgreSQL-style syntax. MySQL and SQLite usually accept the same ADD COLUMN form. SQL Server uses ADD without the word COLUMN.
Why add a column?
A column stores one attribute for each row in a table. Use ALTER TABLE when the table already exists and its structure must change.
For example, a customer table might need to store email addresses:
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
ALTER TABLE customers
ADD COLUMN email VARCHAR(255);The ALTER TABLE statement changes the table definition. It does not insert a particular email address. The new column is added to every row, and existing rows receive NULL unless you specify a default value.
Adding defaults and required values
A default is a value the database supplies when an INSERT statement does not provide a value for that column. A NOT NULL rule rejects rows that have no value.
Adding a required column to a table that already contains rows can fail because those rows need a valid value. Add a default so existing rows can be populated:
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';Existing customers receive 'active'. Future inserts also receive 'active' when they omit status.
The exact behavior and cost can vary by database version. Some systems rewrite the whole table, while others store the default efficiently in the schema. Check the database documentation before changing a large production table.
| Column definition | Existing rows | Future inserts that omit the column |
|---|---|---|
| `email VARCHAR(255)` | `NULL` | `NULL` |
| `status VARCHAR(20) DEFAULT 'active'` | Usually `'active'` | `'active'` |
| `status VARCHAR(20) NOT NULL` | May fail | Must provide a value |
Dialect differences
Check the target database before running a migration:
-- PostgreSQL, MySQL, and SQLite
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
-- SQL Server
ALTER TABLE customers ADD phone VARCHAR(30);Some systems also support clauses for placement, generated values, or conditional creation, but those clauses are not portable. Keep migrations specific to the database engine they target.
Exercise
What happens to existing rows when you add email VARCHAR(255) without DEFAULT or NOT NULL?
Show answer
Existing rows receive NULL, and future inserts also receive NULL when they omit the column.