Question presented to candidate: "Walk me through the column constraints you can put in a CREATE TABLE: NOT NULL, DEFAULT and the others. For each, tell me what the database enforces, and what changes when you add one to a table that already has data."
What a strong answer should cover:
- NOT NULL rejects missing values; it is the most common constraint and the one CHECK and UNIQUE do not replace
- DEFAULT is not a constraint on the data: it only supplies a value when the column is omitted (or written as
DEFAULT); an explicit NULL is stored as NULL - The rest of the family: PRIMARY KEY, UNIQUE, CHECK, REFERENCES (foreign key), plus generated columns and identity columns, and column vs table constraints
- Naming constraints with
CONSTRAINT nameso errors and migrations are readable - Adding to a live table:
SET NOT NULLfails if NULLs exist;ADD COLUMN ... NOT NULLneeds a DEFAULT; PostgreSQL 11+ adds a constant default without rewriting the table - Engine differences: SQLite
INTEGER PRIMARY KEYauto-assigns ids, PostgreSQL uses identity columns; SQLite cannot add a column with a non-constant default
Code / implementation expected: Optional β a CREATE TABLE using each constraint, and inserts that show a default being applied versus an explicit NULL.
Schema used by the examples: