Chapter 2 of 7 · 4 practices · 2 min · 4-question quiz
Constraints that protect your data
Let the database reject bad data so every app, script and admin console that writes to it follows the same rules.
Start: Make columns NOT NULL unless null has a real meaning4 practices in this chapter
- 1Make columns NOT NULL unless null has a real meaningEvery nullable column adds a third state your code has to handle, and
NULLdoes not behave like a normal value:NULL = NULLis not true. Most columns should never be empty, so the safe default is… - 2Use foreign keys, and index the referencing columnA foreign key stops orphan rows that point to deleted parents. It is cheap insurance, but it has one gap people often miss.
- 3Enforce uniqueness with constraints, not application checks"Check if the email exists, then insert" has a race: two requests can both pass the check and both insert. Under load, duplicate accounts appear. Only a unique constraint or unique index closes that…
- 4Put simple business rules in CHECK constraintsSimple business rules are cheap to enforce with
CHECK, and they protect you from bugs in any code path, including one-off scripts and manual fixes that skip your app's validation.
Check yourself on this chapter
4 questions, right here once you are signed in. Your progress is saved as you read.