Consider the following sequence of SQL commands executed on a MySQL database with autocommit disabled:
BEGIN; INSERT INTO accounts (id, balance) VALUES (1, 1000); COMMIT; SELECT balance FROM accounts WHERE id = 1;
What will the SELECT query return?
BEGIN; INSERT INTO accounts (id, balance) VALUES (1, 1000); COMMIT; SELECT balance FROM accounts WHERE id = 1;
Think about what COMMIT does to the changes made inside a transaction.
COMMIT saves all changes made in the transaction permanently. So the inserted row with balance 1000 is visible after commit.
Given this sequence:
BEGIN; INSERT INTO accounts (id, balance) VALUES (2, 500); ROLLBACK; SELECT balance FROM accounts WHERE id = 2;
What will the SELECT query return?
BEGIN; INSERT INTO accounts (id, balance) VALUES (2, 500); ROLLBACK; SELECT balance FROM accounts WHERE id = 2;
ROLLBACK cancels all changes made in the current transaction.
ROLLBACK undoes the INSERT, so the row with id 2 does not exist after rollback.
Choose the correct statement about transactions in MySQL:
Recall the purpose of COMMIT and ROLLBACK in transactions.
COMMIT saves all changes made in the transaction permanently. ROLLBACK undoes changes. BEGIN starts a transaction but does not lock the entire database. Autocommit mode controls automatic commits.
Which option contains a syntax error in MySQL transaction commands?
Option A: BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT; Option B: START TRANSACTION; UPDATE accounts SET balance = balance + 100 WHERE id = 2; ROLLBACK; Option C: BEGIN TRANSACTION; DELETE FROM accounts WHERE id = 3; COMMIT; Option D: BEGIN; INSERT INTO accounts (id, balance) VALUES (4, 200); COMMIT;
Check the exact syntax MySQL accepts for starting transactions.
MySQL uses either BEGIN or START TRANSACTION to start a transaction. 'BEGIN TRANSACTION' is not valid syntax in MySQL.
A developer runs this code:
BEGIN; UPDATE accounts SET balance = balance + 100 WHERE id = 1; -- forgot to COMMIT SELECT balance FROM accounts WHERE id = 1;
After disconnecting and reconnecting, the balance is unchanged. Why?
Think about what happens to uncommitted transactions when the connection closes.
If a transaction is not committed before disconnect, all changes are rolled back automatically. So the UPDATE was lost.