Question presented to candidate:
"Most of the time our code just runs SQL statements one by one and it works. When would you actually reach for BEGIN and COMMIT yourself? Give me real cases from an app like an online shop, and tell me when you would avoid a transaction."
What a strong answer should cover:
- By default each statement runs in its own transaction (autocommit), so a single statement is already atomic; an explicit transaction is for several statements that must succeed or fail together (order + items + stock)
- Business-rule failures: check the row count of a conditional update and
ROLLBACKwhen the rule fails, so no half-written order remains - Performance: many small writes in one transaction avoid one disk flush per commit, so bulk loads are much faster
- Schema migrations: PostgreSQL and SQLite can roll back DDL; MySQL commits implicitly before most DDL
- Read-then-write and consistent reports: a transaction alone at READ COMMITTED does not stop lost updates; pair it with an atomic
UPDATE,SELECT ... FOR UPDATEor a stronger isolation level - When not to: never hold a transaction open across user think time or slow network calls; keep transactions short
Clarifying questions expected:
- Which database and driver? (Some drivers open a transaction implicitly; others autocommit.)
- Can the operation be expressed as one statement, or does it span several tables?
Code / implementation expected: Yes β an order placed as one transaction, and a rollback when a stock check fails.
Schema used by the examples: