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:
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