CONSISTENCY
Let me explain how database maintains valid data using accounts table
First, we already have accounts table with a rule:
balance >= 0
since, this is a constraint.. database will not allow negative balance.
Initial data:
Alice = 1000
Bob = 500
Now we try to break the rule by deducting more money than available.
UPDATE accounts
SET balance = balance - 2000
WHERE name = 'Alice';
since, Alice has only 1000.. after deduction it becomes -1000.. which is not allowed.
Result:
ERROR will come
since, CHECK (balance >= 0) constraint fails.. so database stops the query.
Now we try direct update to negative value.
UPDATE accounts
SET balance = -500
WHERE name = 'Bob';
since, we are directly setting negative value.
Result:
ERROR will come
since, again constraint is violated.. so update will not happen.
Now we check data again:
SELECT * FROM accounts;
Alice = 1000
Bob = 500
since, invalid operations are rejected.. so data remains unchanged.
Now we try inside transaction.
BEGIN;
UPDATE accounts
SET balance = balance - 2000
WHERE name = 'Alice';
COMMIT;
since, constraint fails.. transaction will not complete.
Result:
transaction fails and nothing changes
since, database will not allow invalid state even inside transaction.
Final understanding:
since, database has constraints like CHECK (balance >= 0)..
it automatically prevents wrong data like negative balance
this is schema level protection
but,
checking if user has enough balance before transfer
should be handled in application or transaction logic
so,
database = prevents invalid data
application = controls business logic
because of this:
money will not go negative
data stays consistent
system remains safe
Comments
Post a Comment