Sobes.tech
Junior — Middle

How is data version control managed in a database?

sobes.tech AI

Answer from AI

Data version control in a database is usually implemented through record versioning. This allows tracking changes and preventing conflicts during concurrent access.

Main approaches:

  • Full versioning: each record version is stored as a separate row with a version number or timestamp.
  • Optimistic locking: the table has a version field (e.g., an integer counter). When updating, it checks that the version has not changed since reading; otherwise, the operation is rolled back.

Example in Python using SQLAlchemy:

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Document(Base):
    __tablename__ = 'documents'
    id = Column(Integer, primary_key=True)
    content = Column(String)
    version = Column(Integer, default=1)

# When updating:
# 1. Read the current version
# 2. Attempt to update, specifying WHERE version = current version
# 3. If the update is successful, increment the version
# 4. Otherwise — conflict, need to retry or handle the error

Thus, the system controls data integrity and allows rolling back to previous versions if necessary.