Consistency: Maintaining Database Invariants
What you'll learn: How consistency guarantees in ACID databases ensure that all rules and constraints remain valid across every transaction.
The Core Idea
Consistency means that every transaction moves the database from one valid state to another valid state. Your database enforces rules (called invariants) like "account balances can't be negative" or "every order must have a valid customer ID." The consistency property ensures these rules are never broken, even when multiple transactions happen simultaneously.
Think of consistency like a building inspector who checks that construction follows all building codes. Before any changes are approved (committed), the inspector verifies that nothing violates the rules. If something's wrong, the entire change is rejected.
How It Works
When you define a schema with constraints — primary keys, foreign keys, unique constraints, check constraints, triggers — the database enforces these automatically. Before committing a transaction, the database validates that:
- All constraints are satisfied
- Data types match expectations
- Foreign keys reference existing records
- Custom business rules (via triggers or checks) hold true
If any rule is violated, the transaction fails and rolls back completely (thanks to atomicity). This prevents invalid data from ever entering your database.
Example Invariant
Consider a banking database with a rule: "Total money in all accounts must equal total deposits minus total withdrawals." Consistency ensures this invariant holds true after every transaction. If a transfer operation somehow created money out of thin air, consistency would detect the violation and reject the transaction.
Key Takeaway: Consistency guarantees that your database enforces all defined rules and constraints, ensuring data remains valid and trustworthy across every transaction—invalid states are impossible, not just unlikely.