← Back to SQL, page 21

sql-0403 · Easy fresher

Design the database side of a shopping cart that survives logins and expires abandoned carts.

Store carts with an owner (customer_id or an anonymous token), status and updated_at, and cart_items with product, quantity and the price shown when added. On login, merge the anonymous cart into the customer's cart. A scheduled job marks carts idle for N days as abandoned and deletes very old ones.

Full answer
text
carts(id, customer_id NULL, anon_token UNIQUE NULL, status, created_at, updated_at,
      CHECK (customer_id IS NOT NULL OR anon_token IS NOT NULL))
cart_items(cart_id FK, product_id FK, qty CHECK (qty > 0), price_at_add_cents,
           PRIMARY KEY (cart_id, product_id))
  • Adding the same product twice upserts the item and increases qty.
  • price_at_add_cents lets the UI warn when the price changed; checkout uses the current price.
  • Merging on login: upsert each anonymous item into the customer cart, summing quantities, then delete the anonymous cart, all in one transaction.
  • A partial unique index allows only one active cart per customer.
  • Abandoned carts feed reminder emails; then retention removes them.

Stock is not reserved at add-to-cart time in most shops; reservation happens at checkout, which keeps carts cheap.

Key points

  • Carts owned by a customer or anonymous token
  • Upsert items by product
  • Merge carts on login in one transaction
  • One active cart per customer
  • Expire abandoned carts

Common mistakes

  • Storing carts only in browser storage
  • Reserving stock when items are added

Follow-ups

  • How would you handle a product that goes out of stock in a cart?
  • How would you compute cart abandonment rate?

Tips

  • Describe the merge step