← Back to SQL, page 23

sql-0442 · Hard senior

A finance report reads several tables and must reflect one consistent moment, while orders keep arriving. How do you guarantee that?

Run all the report's queries in one transaction at REPEATABLE READ (PostgreSQL) or inside one read transaction in SQLite WAL mode, so every query sees the same snapshot. Under READ COMMITTED, each statement sees a new snapshot, and totals across tables can disagree. A defined cut-off timestamp is still needed for business meaning.

Full answer

The problem under READ COMMITTED (PostgreSQL's default): query 1 sums orders, an order commits, query 2 sums payments including that order's payment. The report now shows payments without the matching order.

Fix in PostgreSQL:

text
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT SUM(total) FROM orders WHERE placed_at < :cutoff;
SELECT SUM(amount) FROM payments WHERE paid_at < :cutoff;
COMMIT;

Every statement sees the snapshot taken at the first query. SERIALIZABLE READ ONLY DEFERRABLE waits for a snapshot that is guaranteed free of serialization anomalies, useful for long reports.

In SQLite with WAL, a read transaction (BEGIN followed by the first SELECT) also keeps one snapshot until it ends, while writers continue on the WAL.

Snapshots fix consistency between queries; the cut-off timestamp fixes which business events belong in the period. Long snapshots on a busy PostgreSQL primary delay vacuum, so run them on a replica or keep them short. Described here, not run.

Key points

  • READ COMMITTED gives each statement a new snapshot
  • REPEATABLE READ keeps one snapshot per transaction
  • SQLite WAL read transactions also hold a snapshot
  • Use a business cut-off as well
  • Long snapshots delay vacuum

Common mistakes

  • Running report queries in separate transactions
  • Relying on query speed to avoid inconsistency

Follow-ups

  • What does READ ONLY DEFERRABLE do?
  • How would you run this on a replica?

Tips

  • Show where totals can disagree