SQL Transactions


SQL Transactions Interview with follow-up questions

1. Can you explain what a SQL transaction is?

A SQL transaction is a sequence of one or more SQL statements that execute as a single logical unit of work. Either all statements in the transaction succeed and their changes are permanently saved, or none of them take effect — there is no partial outcome.

The classic example:

START TRANSACTION;

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

COMMIT;  -- both changes saved permanently

If the second UPDATE fails (e.g., account 2 doesn't exist), a ROLLBACK undoes the first UPDATE too — the database is left in its original state.

Transaction lifecycle:

  1. BEGIN / START TRANSACTION — start the transaction
  2. Execute SQL statements
  3. COMMIT — permanently save all changes
  4. OR ROLLBACK — undo all changes since the transaction began

Why transactions matter: Without transaction control, a system crash between the debit and credit would leave one account debited with no corresponding credit — a corrupt state. Transactions prevent this.

ACID properties govern transaction guarantees:

  • Atomicity — all or nothing
  • Consistency — valid state before and after
  • Isolation — concurrent transactions don't interfere
  • Durability — committed changes survive crashes

Implicit vs explicit transactions: Some databases (MySQL in autocommit mode, SQL Server) auto-commit every statement as its own transaction unless you explicitly begin one.

↑ Back to top

Follow-up 1

What are the properties of a SQL transaction?

The properties of a SQL transaction are commonly referred to as ACID properties:

  • Atomicity: This property ensures that either all the operations within a transaction are successfully completed, or none of them are. If any operation fails, the entire transaction is rolled back and the database is left unchanged.

  • Consistency: This property ensures that a transaction brings the database from one consistent state to another. It enforces any integrity constraints or rules defined on the database.

  • Isolation: This property ensures that each transaction is executed in isolation from other transactions. Changes made by one transaction are not visible to other transactions until the changes are committed.

  • Durability: This property ensures that once a transaction is committed, its changes are permanent and will survive any subsequent failures, such as power outages or system crashes.

Follow-up 2

Can you provide an example of a SQL transaction?

Sure! Here's an example of a SQL transaction:

BEGIN TRANSACTION;

UPDATE Customers SET Balance = Balance - 100 WHERE CustomerId = 1;

INSERT INTO Transactions (CustomerId, Amount, Type) VALUES (1, 100, 'Withdrawal');

COMMIT;

Follow-up 3

What happens if a transaction fails in between?

If a transaction fails in between, all the changes made by the transaction are rolled back. This means that any modifications made to the database within the transaction are undone, and the database is left in its original state before the transaction started. This ensures that the database remains consistent and does not contain any partially completed or invalid transactions.

Follow-up 4

What is the role of COMMIT and ROLLBACK in SQL transactions?

In SQL transactions, the COMMIT statement is used to permanently save the changes made within a transaction. Once a COMMIT statement is executed, all the changes made within the transaction are made permanent and visible to other transactions.

On the other hand, the ROLLBACK statement is used to undo all the changes made within a transaction and restore the database to its state before the transaction started. It is typically used when a transaction encounters an error or needs to be cancelled for any reason. The ROLLBACK statement ensures that the database remains consistent and does not contain any partially completed or invalid transactions.

2. What are the ACID properties in SQL transactions?

ACID is the set of four properties that guarantee reliable transaction processing in a relational database:

Atomicity A transaction is treated as a single, indivisible unit. Either all operations within it succeed, or none do. If any statement fails, the entire transaction is rolled back.

Example: Transferring money — the debit and credit must both succeed or both fail.

Consistency A transaction brings the database from one valid state to another valid state. All data integrity rules (constraints, triggers, cascades) must be satisfied before and after the transaction. A transaction that would violate a constraint is rolled back.

Example: A foreign key constraint prevents an order from referencing a non-existent customer.

Isolation Concurrent transactions execute as if they were running serially — each transaction is isolated from the intermediate states of others. The degree of isolation is controlled by the isolation level (READ COMMITTED, REPEATABLE READ, SERIALIZABLE, etc.).

Example: Two users simultaneously reading and updating an account balance see consistent values, not each other's in-progress changes.

Durability Once a transaction is committed, its changes are permanent and survive system crashes or power failures. Achieved via write-ahead logging (WAL) or redo logs — changes are written to durable storage before being acknowledged.

Interview follow-up: How does each property fail without the guarantee?

  • Without atomicity: partial updates corrupt the database
  • Without consistency: constraints can be violated mid-transaction
  • Without isolation: dirty reads, non-repeatable reads, phantom reads
  • Without durability: committed data can be lost after a crash
↑ Back to top

Follow-up 1

Can you explain each property in detail?

Sure!

  1. Atomicity: Atomicity ensures that a transaction is treated as a single, indivisible unit of work. Either all the operations within a transaction are successfully completed, or none of them are. If any part of the transaction fails, the entire transaction is rolled back, and the database remains unchanged.

  2. Consistency: Consistency ensures that a transaction brings the database from one consistent state to another. It enforces the integrity constraints and rules defined on the database, ensuring that the data remains valid and consistent throughout the transaction.

  3. Isolation: Isolation ensures that concurrent transactions do not interfere with each other. Each transaction is executed in isolation, as if it were the only transaction running on the database. This prevents data inconsistencies and ensures the correctness of the transaction results.

  4. Durability: Durability guarantees that once a transaction is committed, its changes are permanent and will survive any subsequent failures, such as power outages or system crashes. The changes made by a committed transaction are stored in non-volatile memory, typically disk storage, to ensure their durability.

Follow-up 2

Why are these properties important?

The ACID properties are important for ensuring the reliability, consistency, and integrity of database transactions. They provide guarantees that transactions are executed correctly and that the database remains in a consistent state even in the presence of failures or concurrent access. These properties are crucial for applications that require data integrity, such as financial systems, e-commerce platforms, and any system where data consistency is critical.

Follow-up 3

How does SQL ensure these properties are maintained during a transaction?

SQL ensures the ACID properties through various mechanisms:

  1. Atomicity: SQL uses transaction logs and rollback mechanisms to ensure atomicity. If a transaction fails, the changes made by the transaction can be rolled back using the transaction log.

  2. Consistency: SQL enforces integrity constraints, such as primary key constraints, foreign key constraints, and check constraints, to ensure data consistency. These constraints are checked before and after each transaction to maintain consistency.

  3. Isolation: SQL provides different isolation levels, such as Read Uncommitted, Read Committed, Repeatable Read, and Serializable, to control the level of concurrency and isolation between transactions. These isolation levels prevent dirty reads, non-repeatable reads, and phantom reads.

  4. Durability: SQL ensures durability by writing the changes made by a committed transaction to disk or other non-volatile storage. This ensures that the changes survive any subsequent failures and can be recovered in case of a system crash.

3. What is the difference between implicit and explicit transactions in SQL?

Implicit transactions are started automatically by the database for each individual SQL statement. The statement executes and commits (or rolls back on error) without the developer explicitly writing BEGIN or COMMIT.

This is the behavior of autocommit mode, which is the default in MySQL and most databases:

-- In autocommit mode, each statement is its own transaction:
UPDATE employees SET salary = 90000 WHERE id = 5;  -- auto-committed immediately
DELETE FROM logs WHERE created_at < '2025-01-01';   -- auto-committed immediately

There is no way to roll back an implicit transaction once the statement completes.

Explicit transactions are manually delimited by the developer using BEGIN/START TRANSACTION, COMMIT, and ROLLBACK. Multiple statements are grouped into one atomic unit:

BEGIN;  -- or START TRANSACTION

UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;

-- If something goes wrong:
ROLLBACK;

-- Or if everything is correct:
COMMIT;
Aspect Implicit Explicit
Started by Database automatically Developer with BEGIN
Scope One statement One or more statements
Rollback Not possible after completion Possible until COMMIT
Use case Simple, single-statement operations Multi-step operations requiring atomicity

SQL Server note: SQL Server has a third mode — IMPLICIT_TRANSACTIONS ON — where a transaction is automatically started before DML/DDL but requires an explicit COMMIT or ROLLBACK to end it (the opposite of autocommit).

↑ Back to top

Follow-up 1

Can you provide an example of each?

Example of implicit transaction:

INSERT INTO table_name (column1, column2) VALUES (value1, value2);
```Example of explicit transaction:

```sql
BEGIN TRANSACTION;
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
COMMIT;

Follow-up 2

In what scenarios would you use each type?

Implicit transactions are commonly used in simple operations where the database management system handles the transaction automatically. Explicit transactions are used in more complex scenarios where the user needs more control over the transaction, such as when multiple statements need to be executed as a single unit.

Follow-up 3

What are the advantages and disadvantages of each type?

Advantages of implicit transactions:

  • Simplicity: Implicit transactions are automatically handled by the database management system, making them easier to use.

Disadvantages of implicit transactions:

  • Lack of control: Implicit transactions do not provide fine-grained control over the transaction, making it harder to handle exceptions or rollbacks.

Advantages of explicit transactions:

  • Control: Explicit transactions allow the user to have full control over the transaction, including the ability to handle exceptions and rollbacks.

Disadvantages of explicit transactions:

  • Complexity: Explicit transactions require manual management, which can be more complex and error-prone compared to implicit transactions.

4. Can you explain what a deadlock is in the context of SQL transactions?

A deadlock occurs when two or more transactions are each waiting for a lock held by the other, creating a circular dependency where none can proceed.

Classic deadlock scenario:

Time Transaction A Transaction B
T1 Locks Row 1
T2 Locks Row 2
T3 Tries to lock Row 2 → waits
T4 Tries to lock Row 1 → waits

Neither transaction can proceed — A is waiting for B to release Row 2, while B is waiting for A to release Row 1.

How databases handle deadlocks: The database's deadlock detector periodically scans the lock wait graph. When it detects a cycle, it selects one transaction as the deadlock victim and rolls it back, releasing its locks. The other transaction can then proceed.

ERROR: deadlock detected — transaction was chosen as deadlock victim

How to prevent or minimize deadlocks:

  1. Access resources in a consistent order — if all transactions lock Table A before Table B, circular waits cannot form
  2. Keep transactions short — the less time locks are held, the smaller the window for deadlocks
  3. Use lower isolation levels where appropriateREAD COMMITTED with MVCC avoids many locks
  4. Retry on deadlock — application code should catch deadlock errors and retry the transaction
  5. Index properly — poor indexing causes table scans that acquire many more locks than needed

Interview follow-up: What is a livelock? Unlike a deadlock (where transactions are frozen), in a livelock transactions keep responding to each other but make no progress — each backs off when it detects contention, but keeps colliding again.

↑ Back to top

Follow-up 1

What causes a deadlock?

Deadlocks can occur due to the following reasons:

  1. Mutual Exclusion: Each transaction holds exclusive locks on resources that other transactions need.
  2. Hold and Wait: Each transaction holds a lock on a resource while waiting for another resource to be released by another transaction.
  3. No Preemption: Locks cannot be forcibly taken away from a transaction.
  4. Circular Wait: A circular chain of transactions exists, where each transaction is waiting for a resource held by another transaction in the chain.

Follow-up 2

How can deadlocks be prevented?

Deadlocks can be prevented by implementing the following techniques:

  1. Lock Ordering: Ensure that transactions always acquire locks on resources in the same order. This prevents circular dependencies.
  2. Deadlock Detection: Use a deadlock detection algorithm to identify and resolve deadlocks when they occur.
  3. Timeout Mechanism: Set a timeout for transactions, so that if a transaction is unable to acquire a lock within a certain time, it is rolled back to prevent potential deadlocks.
  4. Resource Allocation Graph: Use a resource allocation graph to visualize the dependencies between transactions and resources, and identify potential deadlocks.

Follow-up 3

How does SQL handle deadlocks?

SQL provides mechanisms to handle deadlocks, including:

  1. Deadlock Detection: SQL databases have built-in deadlock detection algorithms that can automatically detect and resolve deadlocks.
  2. Locking and Concurrency Control: SQL databases use locking and concurrency control mechanisms to manage access to resources and prevent deadlocks.
  3. Transaction Rollback: When a deadlock is detected, SQL databases can automatically roll back one or more transactions involved in the deadlock to resolve it.
  4. Transaction Isolation Levels: SQL databases support different transaction isolation levels, such as READ COMMITTED and SERIALIZABLE, which can affect the likelihood of deadlocks occurring.

5. What is the role of the SAVEPOINT command in SQL transactions?

SAVEPOINT creates a named intermediate checkpoint within a transaction to which you can partially roll back without abandoning the entire transaction.

Syntax:

SAVEPOINT savepoint_name;
ROLLBACK TO SAVEPOINT savepoint_name;
RELEASE SAVEPOINT savepoint_name;  -- removes the savepoint (optional)

Example:

BEGIN;

INSERT INTO orders (customer_id, total) VALUES (1, 150.00);  -- step 1

SAVEPOINT after_order;

INSERT INTO order_items (order_id, product_id, qty) VALUES (1, 99, 2);  -- step 2

-- Something went wrong with step 2:
ROLLBACK TO SAVEPOINT after_order;
-- Step 2 is undone, but step 1 (the order) is still in the transaction

INSERT INTO order_items (order_id, product_id, qty) VALUES (1, 42, 1);  -- retry step 2

COMMIT;  -- commits both the order and the corrected item

Key behaviors:

  • Rolling back to a savepoint does not end the transaction — it remains open
  • You can have multiple savepoints within one transaction
  • A ROLLBACK (without TO SAVEPOINT) rolls back the entire transaction including all savepoints
  • RELEASE SAVEPOINT removes the savepoint marker but does not undo any work

Supported in: PostgreSQL, MySQL (within stored procedures and explicit transactions), Oracle, SQL Server (as SAVE TRANSACTION savepoint_name)

Interview use case: Savepoints are useful in stored procedures that process rows in a loop — a failure on one row can be rolled back to the savepoint while the loop continues, rather than aborting the whole batch.

↑ Back to top

Follow-up 1

Can you provide an example of how to use the SAVEPOINT command?

Certainly! Here's an example:

START TRANSACTION;

INSERT INTO table_name (column1, column2) VALUES (value1, value2);

SAVEPOINT my_savepoint;

INSERT INTO table_name (column1, column2) VALUES (value3, value4);

ROLLBACK TO my_savepoint;

COMMIT;

Follow-up 2

What happens when a SAVEPOINT is rolled back?

When a SAVEPOINT is rolled back, all changes made after the SAVEPOINT was created are undone. This includes any INSERT, UPDATE, or DELETE statements executed after the SAVEPOINT. However, changes made before the SAVEPOINT are still committed.

Follow-up 3

Can you nest SAVEPOINT commands?

Yes, SAVEPOINT commands can be nested. This means that you can create multiple SAVEPOINTS within a transaction and roll back to any of them individually. However, it's important to note that rolling back to an outer SAVEPOINT will also roll back any inner SAVEPOINTS.

Live mock interview

Mock interview: SQL Transactions

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.