DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

CONSISTENCY

Step 1: Check initial data
SELECT * FROM accounts;

Explanation:
Alice has 1000 and Bob has 500.
Both balances are valid (not negative).

Step 2: Try to make balance negative directly
UPDATE accounts
SET balance = -100
WHERE name = 'Alice';

Explanation:
Here I am directly trying to set a negative balance.

What happens:
Query fails

Reason:
There is a constraint CHECK (balance >= 0)

So database itself prevents invalid data.

Step 3: Deduct more than available balance
UPDATE accounts
SET balance = balance - 1500
WHERE name = 'Alice';

Explanation:
Alice has only 1000 but I tried to deduct 1500.

What happens:
Query fails

Reason:
Result becomes negative, so CHECK constraint blocks it

Step 4: Valid deduction
UPDATE accounts
SET balance = balance - 500
WHERE name = 'Alice';

Explanation:
This works because balance remains positive.

Step 5: Using transaction (important case)
BEGIN;

UPDATE accounts
SET balance = balance - 1200
WHERE name = 'Alice';

COMMIT;

Explanation:
Here also it fails before commit.

What happens:
Transaction does not complete

Reason:
Constraint is checked during update

Step 6: Application-level check (manual condition)
UPDATE accounts
SET balance = balance - 1200
WHERE name = 'Alice'
AND balance >= 1200;

Explanation:
Here I added a condition to avoid wrong deduction.

What happens:
No rows updated

Reason:
Condition fails, so query is safe

Final Understanding
Database constraint (CHECK balance >= 0) prevents invalid data
It stops negative values automatically
This is schema-level protection

But,

Checking enough balance before deduction should also be handled in query or application
Otherwise transaction may fail

I tested different updates and observed that database constraints prevent negative balances. I also understood that some validations should be handled in queries or application logic to avoid errors.

Top comments (0)