DELAPARRA
Index
Color
NL
Category: SQL

phantom read

Explained by Updated

What is phantom read?

phantom read: Re-running a range query returns new rows that another committed transaction inserted in between. A phantom read happens when a transaction runs the same range query twice and the second time sees extra rows, because another transaction inserted and committed them in between. Counting orders above 100 euros returns 42, then 43 a moment later inside the same transaction. The existing rows did not change; a new one appeared.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about phantom read

What should you keep in mind with phantom read?

Whether this can happen depends on the isolation level. The SERIALIZABLE level prevents it everywhere. PostgreSQL's REPEATABLE READ also prevents it, and MySQL's InnoDB avoids it for normal reads in its default level through snapshots and gap locks. For most applications this is rarely a problem. It matters for checks like "is this time slot still free", where a unique constraint or a lock is the reliable way to prevent double bookings.

What does an example of phantom read look like?

SELECT COUNT(*) FROM orders WHERE total > 100; -- run twice: count grows because a row was inserted

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with P

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.