hi!
to Design a transaction that transfers money from one account to another using the accounts table,
CREATE TABLE accounts (id SERIAL PRIMARY KEY,name TEXT NOT NULL,balance INT NOT NULL CHECK (balance >= 0),last_updated TIMESTAMP DEFAULT current_timestamp);
create a table with attributes id,name,balance to check balance in account,and last_update .then insert values to the table using insert.
INSERT INTO accounts (name, balance) VALUES ('Alice', 1000),('Bob', 500);
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
UPDATE accounts
SET balance = balance + 200
WHERE name = 'Bob';
COMMIT;
the balance from sender in deducted using update and again using update the balance of reciever is added then the transaction is commited to get the updated result.
BEGIN;
UPDATE accounts
SET balance = balance - 100
WHERE name = 'Alice';
UPDATE accounts
SET balances = balance + 100
WHERE name = 'Bob';
ROLLBACK;
here to show Failed Transaction: Breaking the Credit Operation
first the query 1:updating the account by debiting succeeds
the next query 2:updating the accounts by crediting but here the column name is wrong ,so it fails.Due to the failure of query 2 it roolback.
Creating Failed Transaction for Constraint Violation
BEGIN;
UPDATE accounts
SET balance = balance - 2000
WHERE name = 'Alice';
ROLLBACK;
here the debited amount is more than the available balance so,this will trigger the check constraint violation immediatelyand the system will not allow the next step.
Top comments (0)