A report shows a strange total. The sum at the top does not match the rows underneath, but only now and then, and only while orders are being placed. Someone says it might be the isolation level. Nobody in the room is sure what that is, or what yours is set to.
It is worth an afternoon to find out.
When two transactions run at the same time, the database has to decide how much each one can see of the other's unfinished or newly finished work. The SQL standard, from 1992, describes four levels, from loosest to strictest: read uncommitted, read committed, repeatable read and serializable.
The levels are defined by which odd effects they allow. A dirty read is seeing another transaction's change before it has been committed. A non-repeatable read is reading the same row twice in one transaction and getting different values, because someone committed in between. A phantom is running the same query twice and finding new rows the second time.
Your report is probably a case of the second or third. Under read committed, each statement sees the data as it was when that statement started. So a total calculated in one query and rows fetched in another can come from slightly different moments.
The defaults differ between databases, which surprises many people. PostgreSQL, SQL Server and Oracle use read committed by default. MySQL with its usual InnoDB engine uses repeatable read. PostgreSQL also accepts read uncommitted but treats it as read committed. Code that behaves one way on one database can behave differently on another.
You can check yours. In PostgreSQL, run SHOW transaction_isolation. In MySQL 8, run SELECT @@transaction_isolation.
Stricter is not automatically better. Under serializable, the database may refuse to commit a transaction that would have clashed with another, and your code has to be ready to retry it. That is the price of the stronger guarantee.
If you want to go further, read A Critique of ANSI SQL Isolation Levels, a 1995 paper by Berenson and colleagues, which showed the standard's definitions were looser than they looked. Then try it yourself. Open two database sessions side by side, start a transaction in each, and watch what one can see of the other. Ten minutes of that teaches more than any diagram.
– Asael Shinder
