The Real Fullstack

The Phantom Rows

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

高级工程师8 分钟时间线模拟器代码挑战
sqlpostgresqlmysql

此挑战尚未翻译为简体中文,你正在阅读英文版本。

任务:Make the count and the sum describe the same set of rows, at reasonable cost.背景 · 学习目标 ▾

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.

任务: Make the count and the sum describe the same set of rows, at reasonable cost.

学习目标

  • 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.
模拟模拟数据

运行模拟以查看输出。

运行模拟
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)

简化说明

One concurrent insert between the two statements. Costs are illustrative. 教学模型——数字用于说明行为,并非基准测试。

概念

建议先完成

相关挑战

参考资料