Sub topic 4
Setting Defaults and NOT NULL
This chapter covers how to add, change and remove defaults and NOT NULL rules on columns that already exist. It assumes you can write CREATE TABLE with column types, and that you know what NULL means and how UPDATE ... WHERE works. The examples use PostgreSQL syntax, and the differences in MySQL, SQL Server and SQLite are covered in their own section.
Two rules, two jobs
A default is a value the database fills in when an INSERT leaves a column out. A NOT NULL constraint is a rule that rejects any row where the column is NULL. They are independent. A column can have a default and still allow NULL, because someone can insert NULL explicitly. A column can be NOT NULL with no default, and then every insert must supply a value.
The two rules interact when you change a table that already holds rows. Existing rows have to satisfy any new rule, and that causes most of the problems in this chapter.
Adding a NOT NULL column with a default
Suppose customers already has rows. Adding a NOT NULL column with no default fails, because the existing rows would need a value and the database has none to give them. Adding the default fixes this. The database uses it for every existing row.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (id, name) VALUES (1, 'Ada'), (2, 'Grace');
ALTER TABLE customers
ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'active';
SELECT id, name, status FROM customers;Both rows now show active in status. Without the DEFAULT 'active' clause, PostgreSQL would reject the ALTER TABLE with a "contains null values" error on this table, because it already has rows. On an empty table the same statement would succeed.
Changing a default on an existing column
To change the default of a column that already exists, use SET DEFAULT. To remove it, use DROP DEFAULT.
ALTER TABLE customers ALTER COLUMN status SET DEFAULT 'pending';
ALTER TABLE customers ALTER COLUMN status DROP DEFAULT;A default is only applied when a row is inserted. Changing it does not touch rows that are already stored. After the first statement above, Ada and Grace still have active, and only new inserts get pending. If you want to change old rows too, you must run an UPDATE.
Making an existing column NOT NULL
This is the harder case. The column already exists, it may contain NULL values, and you want to forbid them. If any NULL is still present, the statement fails. The safe order has three steps:
- Find or choose a value for the
NULLrows. - Fill them in with
UPDATE. - Add the constraint.
ALTER TABLE customers ADD COLUMN country CHAR(2);
UPDATE customers SET country = 'US' WHERE country IS NULL;
ALTER TABLE customers ALTER COLUMN country SET NOT NULL;
ALTER TABLE customers ALTER COLUMN country SET DEFAULT 'US';Setting the default last is a choice, not a requirement. It means the backfill value and the future default are stated separately, so you can decide each one on purpose.
To check for leftover NULL values before you add the constraint, run a count:
SELECT COUNT(*) FROM customers WHERE country IS NULL;A result of 0 means SET NOT NULL can succeed. On a busy table, new rows with NULL can arrive between the check and the ALTER. Setting a default first, or deploying application code that always writes the column, closes that gap.
Removing NOT NULL
Allowing NULL again is simple and never fails because of existing data:
ALTER TABLE customers ALTER COLUMN country DROP NOT NULL;Dialect differences
The idea is the same everywhere, but the syntax is not. The table shows how each system changes one aspect of a column.
| Task | PostgreSQL | MySQL | SQL Server | SQLite |
|---|---|---|---|---|
| Set a default | `ALTER COLUMN c SET DEFAULT v` | `ALTER COLUMN c SET DEFAULT v` | `ADD CONSTRAINT name DEFAULT v FOR c` | Not supported on an existing column |
| Drop a default | `ALTER COLUMN c DROP DEFAULT` | `ALTER COLUMN c DROP DEFAULT` | `DROP CONSTRAINT name` | Not supported on an existing column |
| Add NOT NULL | `ALTER COLUMN c SET NOT NULL` | `MODIFY COLUMN c type NOT NULL` | `ALTER COLUMN c type NOT NULL` | Not supported on an existing column |
| Drop NOT NULL | `ALTER COLUMN c DROP NOT NULL` | `MODIFY COLUMN c type NULL` | `ALTER COLUMN c type NULL` | Not supported on an existing column |
MySQL and SQL Server need the full data type again when you change nullability, so you must restate it correctly. SQL Server stores a default as a named constraint, so you should name it when you create it. Without a name, SQL Server generates one, and you have to look it up before you can drop the default.
-- SQL Server
ALTER TABLE customers
ADD CONSTRAINT df_customers_country DEFAULT 'US' FOR country;
ALTER TABLE customers DROP CONSTRAINT df_customers_country;SQLite supports ADD COLUMN with NOT NULL, but only if you also give a non-NULL default. For any other change to nullability or defaults, the usual route is to create a new table, copy the rows across, drop the old table and rename the new one.
Common errors and gotchas
- Column contains null values. You ran
SET NOT NULLwhileNULLrows remained. Backfill first, then retry. - Default not applied to old rows.
SET DEFAULTonly affects future inserts. UseUPDATEfor existing rows. - MODIFY drops your default in MySQL.
MODIFY COLUMNreplaces the whole column definition. If you leave out theDEFAULT, the default is removed. Restate everything you want to keep. - Nullability changes silently in SQL Server. If you run
ALTER COLUMN c VARCHAR(200)without sayingNULLorNOT NULL, the column's nullability can change to the session or database default, not what it was before. Always state it. - Explicit NULL ignores a default.
INSERT ... VALUES (..., NULL)storesNULL, not the default. To get the default, omit the column or write the keywordDEFAULT. - Dynamic defaults. A default like
CURRENT_TIMESTAMPis evaluated at each insert. Adding it to an existing column does not stamp old rows with a meaningful time.
Putting it together
A reasonable routine for tightening a column on a live system is:
- Add the column as nullable, or with a default if the default is truly correct for old rows.
- Deploy code that writes the column on every insert.
- Backfill old rows in batches.
- Verify with a
COUNT(*) ... IS NULLquery. - Add
NOT NULL.
Each step can be checked and, if needed, reversed with DROP NOT NULL or DROP DEFAULT, which is why the sequence is safer than one large statement.
Exercise
A table invoices already holds 10,000 rows. You run ALTER TABLE invoices ADD COLUMN currency CHAR(3) NOT NULL; in PostgreSQL and it fails. Write a sequence of statements that adds currency as NOT NULL with every existing invoice set to 'USD', and explain why the original statement failed. After your change, what currency does a new row get if the insert omits the column?
Show answer
The original failed because the existing 10,000 rows would have had no value, so they would be NULL, which violates NOT NULL. One valid fix is a single statement: ALTER TABLE invoices ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD';. The three-step version also works: ALTER TABLE invoices ADD COLUMN currency CHAR(3); then UPDATE invoices SET currency = 'USD' WHERE currency IS NULL; then ALTER TABLE invoices ALTER COLUMN currency SET NOT NULL;. With the single-statement version, a new row that omits the column gets 'USD' because the default stays on the column. With the three-step version, no default was set, so an insert that omits currency would fail unless you also run ALTER TABLE invoices ALTER COLUMN currency SET DEFAULT 'USD';.