Skip to main content

How do you start a transaction in SQL?

In SQL, a transaction starts with:

sql
BEGIN TRANSACTION;

or simply

sql
START TRANSACTION;

After that, you run the queries you need, e.g. INSERT, UPDATE, DELETE. Once everything succeeds, you need to commit the changes:

sql
COMMIT;

If an error occurs or you need to cancel, you roll back:

sql
ROLLBACK;

Example

sql
START TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;

If something goes wrong, you can replace COMMIT with ROLLBACK, and the database returns to its original state.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.