A Guide to SQL Transactions with Effective Error Handling

ยท

2 min read

In this article, Iโ€™m going to be talking about transactions and error handling in SQL.

Transactions

A transaction is a sequence of SQL operations executed as a single unit. If all operations are successful then the transaction is committed. If any operation fails then the transaction is rolled back to avoid partial changes.

There are four key transaction commands,

  • START - Starts a transaction.

  • COMMIT - Saves all changes made during the transaction.

  • ROLLBACK - Undoes all changes if an error occurs.

  • SAVEPOINT - Creates a point to which a transaction can be rolled back.

Lets see a basic example of transactions using SQL,

START TRANSACTION;

UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;

COMMIT;

If both operations are successful then the record will be permanently saved to the database. With ROLLBACK, if something goes wrong with one of the operations, all changes in the transaction will be cancelled and the database is rolled back to the previous state before the transaction started.

START TRANSACTION;

UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;

ROLLBACK;

SAVEPOINT allows rolling back to a specific point in a transaction,

START TRANSACTION;

UPDATE accounts SET balance = balance - 300 WHERE account_id = 1;
SAVEPOINT after_first_transaction;

UPDATE accounts SET balance = balance + 300 WHERE account_id = 2;

ROLLBACK TO after_first_transaction; -- Rolls back only the second update

COMMIT;

Error Handling

SQL does not have a direct TRY CATCH like programming languages, but we can handle errors using stored procedures and error codes. Here is an example,

DELIMITER $$

CREATE PROCEDURE TransferMoney()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
        ROLLBACK;
        SELECT 'Transaction failed, changes rolled back.' AS message;
    END;

    START TRANSACTION;

    UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
    UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;

    COMMIT;
    SELECT 'Transaction successful' AS message;
END $$

DELIMITER ;

Here if any query fails, the handler rolls back changes and displays an error message.

ย