# Topic 28: Constraints & Invariants
NOT NULL, UNIQUE, CHECK, DEFAULT constraints, domain validation, and database-level business rules.
1. Definition
Constraints are database-level declarations that enforce data integrity rules on table columns, rejecting any INSERT or UPDATE that violates them.
2. Explain Like I'm 5
Constraints are the security rules of a building: "no entry without a badge" (NOT NULL), "every badge must be distinct" (UNIQUE), and "must be at least 18 years old" (CHECK).
3. Animation & Visual Simulation
Interactive Engine TraceConstraints & Invariants Visual Simulator
ALTER TABLE products ADD CONSTRAINT chk_price CHECK (price > 0.00);Active InputStep 1: Input & Parsing Stage
Initiating Constraints & Invariants
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
A user profile table ensuring valid usernames, positive account balances, and verified status.
| Column | Constraint | Rule |
|---|---|---|
| username | UNIQUE NOT NULL | Must exist and be unique |
| balance | CHECK (balance >= 0) | No negative balances |
| status | DEFAULT 'active' | Auto-defaults to active |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE TABLE bank_accounts (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_number VARCHAR(20) UNIQUE NOT NULL,
balance NUMERIC(12, 2) NOT NULL DEFAULT 0.00
CONSTRAINT chk_positive_balance CHECK (balance >= 0.00),
account_type VARCHAR(10) NOT NULL
CHECK (account_type IN ('checking', 'savings', 'investment'))
);6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| NOT NULL | Prohibits NULL values in the specified column. |
| UNIQUE | Guarantees that all non-null values in the column are distinct. |
| CHECK | Validates arbitrary boolean conditions (e.g. price > 0). |
| DEFAULT | Supplies a fallback value if omitted during INSERT. |
| Database-level vs App-level enforcement | Database constraints guarantee integrity across all services, scripts, and direct database updates. |
| Deferrable constraints for cyclic dependencies | DEFERRABLE INITIALLY DEFERRED constraints postpone integrity checks until transaction commit time. |
7. Deep Dive: Database Constraints vs Application Validation
Application code validation is vulnerable to race conditions, multi-service bugs, and direct SQL script executions. Database-level constraints are ACID invariants enforced by the storage engine, making corrupted data physically impossible.
-- Guaranteed invariant across all microservices:
ALTER TABLE users ADD CONSTRAINT chk_email_format
CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');8. Advantages & Disadvantages
Advantages
- •Single source of truth for invariants.
- •Prevents corrupted records regardless of which microservice writes the data.
Disadvantages & Trade-offs
- •Complex multi-table constraints require triggers or serialized transactions.
9. Common Interview Questions
Q1.Why should business invariants be enforced via database constraints rather than only in application code?
Application code is never the sole entry point to data: background worker jobs, direct SQL patches by DBAs, ETL data pipelines, and microservices all touch the database. If validation only exists in code, a bug or race condition in one service corrupts data permanently. Database constraints guarantee mathematical consistency regardless of how data enters the engine.
Q2.What are Deferrable Constraints (DEFERRABLE INITIALLY DEFERRED) and when are they required?
Normally, constraints are checked immediately after each SQL statement. If table A has an FK referencing table B, and table B has an FK referencing table A (a circular dependency), inserting into either table throws an FK violation! A deferrable constraint postpones validation until the transaction issues COMMIT, allowing both rows to be inserted before verification.
Q3.Can a UNIQUE constraint contain multiple NULL values in SQL?
Yes! In standard ANSI SQL and PostgreSQL, NULL is not equal to NULL (NULL != NULL). Therefore, multiple rows with NULL in a unique column do NOT violate the unique constraint. If you want a column to allow only one NULL value, you must enforce it with a unique partial index: CREATE UNIQUE INDEX idx ON tbl(col) WHERE col IS NOT NULL;
Q4.What is a CHECK constraint and what are its performance characteristics?
A CHECK constraint evaluates a boolean expression on every INSERT and UPDATE: CHECK (price > 0 AND discount <= price). CHECK constraints evaluate in memory in nanoseconds before the tuple is written to the 8 KB page slot. If the condition evaluates to FALSE, the statement aborts. Note: if the expression evaluates to UNKNOWN (due to a NULL), the check constraint PASSES!
Q5.How do you add a NOT NULL or CHECK constraint to a table with 100,000,000 rows without locking it?
Adding a constraint with standard ALTER TABLE acquires an AccessExclusiveLock and scans all 100M rows, locking out readers and writers for minutes. In PostgreSQL, you add the constraint with NOT VALID (instant metadata lock), and then run ALTER TABLE tbl VALIDATE CONSTRAINT name; which validates existing rows with only a weak ShareUpdateExclusiveLock that allows concurrent reads and writes!
10. Interview-Ready Answer
“Constraints enforce schema-level invariants including NOT NULL, UNIQUE, CHECK, and DEFAULT. Defining invariants at the database layer ensures data integrity cannot be bypassed by application-level race conditions or multi-service bugs.”
11. Quick Test
What happens if you execute: INSERT INTO bank_accounts (account_number, balance) VALUES ('A100', -50.00); when balance has CHECK (balance >= 0)?