Sobes.tech
Junior — Middle

What will be the result if two transactions try to update the same record in the database simultaneously?

sobes.tech AI

Answer from AI

When two transactions attempt to update the same record in a database simultaneously, the outcome depends on the transaction isolation level and the locking mechanism in the DBMS.

Typically, the following occurs:

  • The first transaction acquires a lock on the record and updates it.
  • The second transaction waits for the lock to be released or encounters a lock error (deadlock).
  • If the second transaction cannot acquire the lock, it may be rolled back or retried.

This prevents race conditions and ensures data integrity.

Example in Python using SQLite (which supports database-level locks):

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

try:
    cursor.execute('BEGIN TRANSACTION')
    cursor.execute('UPDATE users SET balance = balance + 100 WHERE id = 1')
    conn.commit()
except sqlite3.OperationalError:
    conn.rollback()

In real systems with more complex DBMSs (PostgreSQL, MySQL), behavior depends on transaction settings and isolation levels.