← Back to SQL, page 25

sql-0488 · Hard senior

Design tables for a loyalty programme where customers earn points on purchases and the points expire after 12 months.

Store every change as a ledger row (earned, redeemed, expired, adjusted) with its own expiry date for earned rows, and compute the balance from unexpired earned points minus redemptions. Redemptions should consume the oldest expiring points first, recorded as allocations, so the balance by expiry bucket stays explainable. A nightly job writes expiry rows, or queries ignore expired points directly.

Full answer

Illustrative PostgreSQL design (example SQL, not run here):

sql
CREATE TABLE point_ledger (
  id          bigserial PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers(id),
  kind        text NOT NULL CHECK (kind IN ('earn', 'redeem', 'expire', 'adjust')),
  points      integer NOT NULL,            -- positive for earn, negative for the rest
  expires_on  date,                        -- only for 'earn' rows
  order_id    bigint,
  created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON point_ledger (customer_id, created_at);

Balance now: the sum of all points for the customer, after expiry rows are written. If expiry is applied lazily instead, a query sums earn rows whose expires_on is in the future and subtracts redemptions, which is only correct when redemptions are matched to the earn rows they consumed.

Matching redemptions to earn rows is the hard part. The usual rule is first-expiring-first-out: when a customer redeems 300 points, a function walks their earn rows ordered by expires_on, and an allocations(redeem_id, earn_id, points) table records how much of each earn row was used. The unused remainder of an earn row is then points - sum(allocations), and the expiry job writes one expire row for that remainder on the expiry date.

Design points: the ledger is append-only, so history is never lost and disputes can be answered row by row; redemptions run in a transaction that locks the customer's earn rows with FOR UPDATE to prevent two checkouts spending the same points; a cached balance column on the customer, if needed for speed, is updated in the same transaction and verified by a nightly reconciliation against the ledger. Reversals of a returned order are new rows, never edits.

Key points

  • Append-only ledger of earn, redeem and expire rows
  • Expiry date on earned points
  • First-expiring-first-out allocation of redemptions
  • Lock earn rows while redeeming
  • Reconcile any cached balance

Common mistakes

  • Storing only a balance column
  • Letting redemptions ignore which points they consume

Follow-ups

  • How would you show a customer which points expire next month?
  • How would a returned order reverse earned points that were already spent?

Tips

  • Explain why a plain balance is not enough