Consistency: Maintaining Database Invariants
What You'll Learn
You'll learn how the consistency property ensures that every transaction transforms the database from one valid state to another, preserving all defined rules and constraints.
Understanding Consistency
While atomicity ensures transactions complete fully or not at all, consistency ensures that when they do complete, they leave the database in a valid state according to all defined rules.
Think of consistency like traffic laws: atomicity ensures you either complete your entire journey or stay home, but consistency ensures that during your journey, you never drive on the wrong side of the road or run red lights. The database has "rules of the road" that must always be obeyed.
Database Invariants
Invariants are rules that must always hold true:
- Constraints: Primary keys, foreign keys, unique constraints, NOT NULL requirements
- Business rules: Account balances can't be negative, order totals must match line items
- Triggers: Automated checks that fire on data changes
- Data types: Values must match column types
When you execute a transaction, consistency guarantees that:
- The database starts in a valid state
- All operations respect the rules
- The database ends in a valid state
Example Scenario
If you transfer $100 between accounts, consistency ensures:
- Both accounts exist (foreign key constraints)
- Neither account goes negative (CHECK constraint)
- The total money in the system stays the same (business rule)
If any rule would be violated, the entire transaction must be rolled back, keeping the database in its previous valid state.
Key Takeaway: Consistency is the "C" in ACID that ensures transactions respect all database rules and constraints, preventing the database from ever entering an invalid state where invariants are violated.