DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Consistency

The problem is
We are managing account balances in a system
Balance should never become negative
Invalid operations must be rejected

Initial Data
Alice has 1000
Bob has 500

Database Rule
Balance has a constraint balance greater than or equal to 0
This ensures invalid values are not allowed

Valid Operation
Deduct 200 from Alice

After update
Alice balance becomes 800

This works because balance is still valid

Error Case 1
Trying to deduct more than available balance
Deduct 1200 from Alice

Database throws error
Check constraint fails

Final state
Alice still has 1000
No change happens

Error Case 2
Directly setting balance to negative
Update balance to minus 100

Database rejects the update
Constraint violation occurs

Final state
Balance remains unchanged

Because
Database enforces rules using constraints
It does not allow invalid data to be stored

Even if query is correct syntactically
It will fail if it breaks defined rules

Database handles structural rules like
Balance should not be negative

But logical rules like
Checking enough balance before transfer
Should be handled in application or transaction logic

Constraints act as a safety layer
They prevent invalid data from entering database

Top comments (0)