What is a CHECK constraint and a DEFAULT constraint?
Quick Answer
A CHECK constraint enforces a Boolean rule on a row's values — CHECK (Price >= 0), CHECK (EndDate > StartDate). A DEFAULT constraint supplies a value when an INSERT doesn't specify the column — DEFAULT (SYSUTCDATETIME()) for a CreatedAt.
A CHECK constraint is a rule on the data itself — price can't be negative, end date has to be after start date — and the engine rejects any insert or update that breaks it. A DEFAULT constraint fills in a value when the insert doesn't provide one, like defaulting a CreatedAt to the current UTC time. One subtlety with CHECK: it lets a row through if the condition is true or unknown, so a CHECK on age still allows a null age unless you also make the column NOT NULL.
CHECKcan reference multiple columns in the same row but not other rows or tables (use a trigger or an indexed view for that).- A
CHECKallows a row through if the expression isTRUEorUNKNOWN(NULL) — soCHECK (Age >= 18)still permitsNULLage. - Constraints are declarative, checked by the engine, visible in metadata, and faster/safer than equivalent trigger logic.
- Keep validation in both the app (good UX) and the database (last line of defence) for critical invariants.