← Back to SQL, page 20

sql-0395 · Medium mid

Design coupon codes that can be redeemed at most 100 times in total and once per customer.

Store coupons with max_redemptions and a redeemed_count, and a redemptions table with a unique (coupon_id, customer_id). Redeem in one transaction: insert the redemption (the unique key enforces once per customer) and increment the counter with a conditional UPDATE ... WHERE redeemed_count < max_redemptions; if no row changes, roll back.

Full answer
text
coupons(id, code UNIQUE, discount, valid_from, valid_to, max_redemptions, redeemed_count DEFAULT 0)
coupon_redemptions(coupon_id, customer_id, order_id, redeemed_at,
                   PRIMARY KEY (coupon_id, customer_id))

Redemption transaction:

  1. INSERT INTO coupon_redemptions ... fails with a unique violation if the customer already used it.
  2. UPDATE coupons SET redeemed_count = redeemed_count + 1 WHERE id = :c AND redeemed_count < max_redemptions AND now() BETWEEN valid_from AND valid_to;
  3. If step 2 changed zero rows, roll back: the coupon is exhausted or expired.

The conditional update makes the limit safe under concurrency, because the row lock serialises competing increments and each re-checks the condition. Counting redemptions with SELECT COUNT(*) and then inserting would let the 101st customer through. If an order is cancelled, delete the redemption and decrement the counter in one transaction, according to the business rule.

Key points

  • Unique key for once per customer
  • Conditional increment for the global limit
  • Both in one transaction
  • Count-then-insert races

Common mistakes

  • Checking the limit with COUNT(*) before inserting
  • Case-sensitive code lookups that confuse users

Follow-ups

  • How would you generate a million unique single-use codes?
  • How would you restore a redemption on refund?

Tips

  • Show why the conditional update is safe