~learn.
0:00 / 1:10
W00 · Databases

One coupon per customer. She used it twice.

transcript

First order coupon. 100 rupees off. One per customer. One customer just used it twice. At the same time, from two devices.

She opens checkout on her phone. And on her laptop. The phone's checkout asks: any earlier uses? Zero. The laptop checks too. Also zero. Both insert a use. Both get 100 off.

But here's the catch. Row locks can't catch this. Each checkout inserted its own new row. No row was written twice. So there was nothing to collide. That's write skew.

The fix is a constraint in the uses table. Unique on customer and coupon. Now the second insert collides with the first, and fails. At any isolation level. The rule now lives in one row the database can check.

No constraint fits your rule? Use Serializable. The database aborts one of them, with error 40001. You retry it.

Don't check rules in your code. Put them where the database can check them.

Full breakdown in the lecture.