← Back to SQL, page 19

sql-0370 · Medium mid

Design storage for documents where users need to see and restore earlier versions.

Keep a documents table for identity and current pointer, and a document_versions table with one immutable row per save (document_id, version number, content, author, created_at) under a unique (document_id, version). Restoring creates a new version copied from an old one, so history is never rewritten.

Full answer
text
documents(id PK, owner_id, current_version INT, created_at)
document_versions(document_id FK, version INT, title, body, author_id, created_at,
                  PRIMARY KEY (document_id, version))

Behaviour:

  • Saving inserts version n+1 and updates current_version in the same transaction; the primary key stops two concurrent saves from both creating version n+1, so one retries.
  • Reading the current document joins on current_version, or a latest view does it.
  • Restoring version 3 inserts a new version whose content copies version 3.

Storage grows with every save; options are storing diffs for large documents, keeping full snapshots every N versions, or pruning old versions by policy. The same pattern (immutable versions plus a current pointer) fits price lists, policies and configuration.

Key points

  • Immutable version rows
  • Unique (document_id, version)
  • Current pointer on the parent
  • Restore by creating a new version
  • Consider diffs or pruning at scale

Common mistakes

  • Overwriting rows and keeping a separate change log only
  • Using timestamps alone as version identifiers

Follow-ups

  • How would you show a diff between versions?
  • How would you handle concurrent edits?

Tips

  • Show how restore preserves history