Skip to content
Back to 50 Concepts
Topic 28 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Constraints & Invariants Visual Simulator

Step 1 of 3
SQL>ALTER TABLE products ADD CONSTRAINT chk_price CHECK (price > 0.00);Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Constraints & Invariants
SQL Input

Initiating Constraints & Invariants

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Security turnstile: Rejects anyone without a valid ticket or who doesn't meet height requirements.

4. Real-World Example

A user profile table ensuring valid usernames, positive account balances, and verified status.

Accounts Constraints
ColumnConstraintRule
usernameUNIQUE NOT NULLMust exist and be unique
balanceCHECK (balance >= 0)No negative balances
statusDEFAULT 'active'Auto-defaults to active
Relational walkthrough: Constraints stop bad data at the database boundary before it reaches disk.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Adding CHECK and UNIQUE constraints
CREATE 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

RuleBehavioral Explanation
NOT NULLProhibits NULL values in the specified column.
UNIQUEGuarantees that all non-null values in the column are distinct.
CHECKValidates arbitrary boolean conditions (e.g. price > 0).
DEFAULTSupplies a fallback value if omitted during INSERT.
Database-level vs App-level enforcementDatabase constraints guarantee integrity across all services, scripts, and direct database updates.
Deferrable constraints for cyclic dependenciesDEFERRABLE 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,}$');
Caution: Never rely solely on frontend or API validation for critical business rules like positive inventory or unique emails.

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

Scenario Question:

What happens if you execute: INSERT INTO bank_accounts (account_number, balance) VALUES ('A100', -50.00); when balance has CHECK (balance >= 0)?

Select your answer: