The Real Fullstack

The Phantom Rows

Both queries ran in the same transaction. How can they disagree about how many orders exist?

Ingeniero sénior8 minSimulador de línea de tiempoReto de código
sqlpostgresqlmysql

Este reto aún no está traducido al Español. Estás leyendo la versión en inglés.

Misión:Make the count and the sum describe the same set of rows, at reasonable cost.Contexto · Objetivos de aprendizaje ▾

Fernway's finance report computes average order value from two queries — a count and a sum — inside one transaction on PostgreSQL. During busy hours the average is slightly wrong, and the totals never reconcile with the accounting export.

Misión: Make the count and the sum describe the same set of rows, at reasonable cost.

Objetivos de aprendizaje

  • Explain phantom reads: the set of rows matching a predicate changes.
  • Understand per-statement vs per-transaction snapshots.
  • Know where engines exceed the SQL standard.
SimulaciónSimulado

Ejecuta la simulación para ver la salida.

Ejecutar simulación
BEGIN;  -- READ COMMITTED: every statement takes a new snapshotSELECT count(*)   AS orders  FROM orders WHERE day = current_date;SELECT sum(total) AS revenue FROM orders WHERE day = current_date;   -- may include rows inserted in betweenCOMMIT;-- options: BEGIN ISOLATION LEVEL REPEATABLE READ;  (one snapshot for the whole transaction in PostgreSQL)--      or: SELECT count(*), sum(total) FROM orders WHERE day = current_date;   (one statement, one snapshot)

Simplificación

One concurrent insert between the two statements. Costs are illustrative. Modelo educativo: los números ilustran un comportamiento, no son benchmarks.

Conceptos

Útil antes de este

Retos relacionados

Referencias