DEV Community

Jonah Blessy
Jonah Blessy

Posted on

Consistency

SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Start by seeing current balances to know the baseline. This helps compare what changes after each operation.


UPDATE accounts 
SET balance = balance - 2000 
WHERE name = 'Alice';
Enter fullscreen mode Exit fullscreen mode

This attempts to reduce balance below zero. It tests whether the database allows invalid balance updates.


SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Check if the update actually went through. The expectation is that constraint should block it.


UPDATE accounts 
SET balance = -100 
WHERE name = 'Bob';
Enter fullscreen mode Exit fullscreen mode


sql

This bypasses calculation and forces an invalid state. Helps confirm if schema-level checks are enforced.

The CHECK (balance >= 0) constraint prevents negative values. PostgreSQL throws an error before committing the change.


BEGIN;

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

COMMIT;
Enter fullscreen mode Exit fullscreen mode

Even inside a transaction, constraint violation should stop execution. Transaction will not commit successfully.


SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Balances should remain unchanged since invalid operation failed. Confirms no partial updates happened.


UPDATE accounts 
SET balance = balance - 200 
WHERE name = 'Alice' AND balance >= 200;
Enter fullscreen mode Exit fullscreen mode

Adds logic to prevent invalid deduction before it happens. This is handled at query/application level.

Constraints act as a final safety net at database level. Application logic prevents bad operations earlier, reducing errors.


SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Ensure all balances are valid and non-negative. Confirms system maintains consistency through both rules and checks.

Top comments (0)