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. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

先に取り組むと役立つ課題

関連する課題

参考資料