Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Transaction Creation | Section
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
SQL Optimization and Query Features
Sectionย 1. Chapterย 3
single

single

bookChallenge: Transaction Creation

Swipe to show menu

When transferring funds between two accounts in a banking system, you must ensure that both the deduction from the source account and the addition to the destination account happen together as a single, indivisible operation. This is where the concept of a transaction comes in: a transaction groups multiple SQL statements so that they either all succeed or none take effect, maintaining atomicity.

To transfer funds, you will work with the bank_accounts table, which contains columns for account_id, owner_name, and balance. The transaction should:

  • Start with a BEGIN statement to initiate the transaction;
  • Check that the source account has enough funds for the transfer;
  • If there are sufficient funds, deduct the amount from the source account and add it to the destination account;
  • If the source account lacks sufficient funds, the transaction should be rolled back, leaving all balances unchanged;
  • Commit the transaction only if all steps succeed.

This approach ensures that no partial updates occur, and the system remains reliable even in the event of errors.

Task

Swipe to start coding

Write a SQL transaction that transfers a specified amount from one account to another in the bank_accounts table. The transaction must be atomic and should roll back if the source account does not have enough funds.

  • Retrieve the balance of the source account and ensure it is greater than or equal to the transfer amount.
  • If sufficient, deduct the transfer amount from the source account.
  • Add the transfer amount to the destination account.
  • Record the transfer in the transfers table.
  • If the source account lacks sufficient funds, roll back the transaction and raise an error.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 1. Chapterย 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt