SET/DROP DEFAULT and SET/DROP NOT NULL
Objectives
By the end of this lesson, you should be able to:
- Add or remove a
DEFAULTon an existing column - Add or remove a
NOT NULLconstraint on an existing column - Explain why
SET NOT NULLcan fail on a table that already has data
💡 Why this matters:
DEFAULTandNOT NULL(Module 3) aren’t fixed forever atCREATE TABLEtime. Requirements change, a column that used to be optional becomes required, or vice versa.
⚠️ A note on verification: every statement and result in this lesson was run against a real, live PostgreSQL 18 database, using the
employeestable from Module 3.
SET DEFAULT and DROP DEFAULT
ALTER TABLE employees ALTER COLUMN department SET DEFAULT 'Unassigned';
INSERT INTO employees (first_name, last_name, email, salary)
VALUES ('Erin', 'Castillo', 'erin.castillo@example.com', 70000);
first_name | department
------------+------------
Erin | Unassigned
department wasn’t mentioned in the INSERT, and picked up the new default. SET DEFAULT only affects future inserts, it doesn’t retroactively change rows already in the table. Removing it is just as direct:
ALTER TABLE employees ALTER COLUMN department DROP DEFAULT;
Future inserts that skip department now store NULL again, exactly like before SET DEFAULT was applied.
SET NOT NULL and DROP NOT NULL
ALTER TABLE employees ALTER COLUMN department SET NOT NULL;
If every existing row already has a real value in department, this succeeds immediately. But if even one row currently has NULL there, it fails:
ALTER TABLE employees ALTER COLUMN department SET NOT NULL;
ERROR: column "department" of relation "employees" contains null values
The fix is to clean up the existing data first, then apply the constraint:
UPDATE employees SET department = 'Unassigned' WHERE department IS NULL;
ALTER TABLE employees ALTER COLUMN department SET NOT NULL;
Removing the constraint doesn’t have this problem, there’s no data to conflict with:
ALTER TABLE employees ALTER COLUMN department DROP NOT NULL;
Try It
- Add a
DEFAULT 'General'to ateamcolumn, insert a row without mentioningteam, and confirm it picked up the default. - Remove that default, insert another row without mentioning
team, and confirm it’sNULLthis time. - Try
SET NOT NULLon a column that currently has at least oneNULLvalue, and confirm you get an error, then clean up theNULLand try again successfully. - Explain, in your own words, why
SET NOT NULLneeds to check existing data, whileSET DEFAULTdoesn’t.
Recap
SET DEFAULTandDROP DEFAULTchange what futureINSERTs fill in automatically, without touching existing rows.SET NOT NULLrequires every existing row to already have a real value, or it fails, existingNULLs need cleaning up first.DROP NOT NULLalways succeeds, removing a constraint never conflicts with existing data.
Next lesson: adding and dropping UNIQUE and CHECK constraints on a table that already exists.