Examples of transactions in SQL
To illustrate how transactions work in SQL, let's look at some examples. Suppose you have a table called accounts that stores the balance of different users. You want to transfer $100 from user A to user B in a transaction. You can use the following SQL statements:
BEGIN TRANSACTION
UPDATE accounts SET balance = balance - 100 WHERE user = 'A'
UPDATE accounts SET balance = balance + 100 WHERE user = 'B'
COMMIT
This transaction ensures that both updates are executed as a unit and that the total balance of the accounts remains the same. If any of the updates fails, the transaction is rolled back and the balance is unchanged.
Now suppose you have another table called orders that stores the details of the orders placed by the users. You want to insert a new order for user A in a transaction, but you also want to check if user A has enough balance to pay for the order. You can use the following SQL statements:
BEGIN TRANSACTION
DECLARE @balance INT
SELECT @balance = balance FROM accounts WHERE user = 'A'
IF @balance >= @order_amount
BEGIN
INSERT INTO orders (user, order_amount, order_date) VALUES ('A', @order_amount, GETDATE())
UPDATE accounts SET balance = balance - @order_amount WHERE user = 'A'
COMMIT
END
ELSE
BEGIN
ROLLBACK
PRINT 'Insufficient balance'
END
END TRANSACTION
This transaction ensures that the order is inserted and the balance is updated only if user A has enough balance to pay for the order. If user A does not have enough balance, the transaction is rolled back and no changes are made to the database.