In digital wallet applications like PhonePe or GPay, it is very important to maintain correct data at all times. Even a small mistake, such as allowing a negative balance, can lead to serious problems like incorrect transactions or money loss. This is where consistency in a database becomes important.
To understand this, I used an accounts table with two users, Alice and Bob. After previous operations, their balances were 800 and 700.
First, I tried to update Aliceโs balance to a negative value directly. When I executed the query, PostgreSQL immediately gave an error and did not allow the update. This happened because of the constraint CHECK (balance >= 0) defined in the table. This constraint ensures that balance can never go below zero.
Next, I tried to deduct more money than Alice had. Since her balance was 800, I attempted to subtract 1000. Again, PostgreSQL rejected the operation because it would result in a negative balance. The database prevented invalid data from being stored.
I also tried performing this operation inside a transaction. Even in that case, the update failed and the transaction did not get committed. The database ensured that no incorrect changes were applied.
After all these failed attempts, I checked the table again. The balances remained unchanged at 800 and 700. This shows that the database maintained a consistent and valid state throughout.
From this experiment, it is clear that PostgreSQL enforces rules using constraints to prevent invalid data. At the same time, in real-world applications, the system should also check the balance before performing a transaction to avoid such errors.
Overall, this shows how consistency is maintained by ensuring that only valid data is stored in the database.
Top comments (0)