DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Consistency

Let’s understand how a database keeps data valid using an accounts table.
Assume the table has a rule like:
balance ≥ 0
This is a constraint which means the database wont allow any negative balance.

Initial data

  1. Alice = 1000
  2. Bob = 500

Trying to break the rule now suppose we try to deduct more money than Alice actually has

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

Alice only has 1000 so this would make her balance -1000 which violates the constraint.
Result:
The database throws an error and rejects the update.

Directly setting a negative value

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

Again this violates the rule.
Result:
The database blocks the query with an error.

Checking the data again
SELECT * FROM accounts;
Alice = 1000
Bob = 500
invalid operations were rejected the data remains unchanged.

Inside a transaction
Now lets try the same invalid update within a transaction:

BEGIN;

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

COMMIT;
Enter fullscreen mode Exit fullscreen mode

the constraint fails the transaction itself fails and does not complete.

Result:

  1. The database uses constraints like CHECK (balance >= 0) to automatically prevent invalid data, such as negative balances.
  2. This is schema-level protection.
  3. But checking whether a user has enough balance before attempting a transfer is still the responsibility of the application or transaction logic.

Big picture
Database - prevents invalid data
Application - handles business rules

Because of this Balances never go negative data stays consistent and the system remains reliable

Top comments (0)