← Back to SQL, page 19

sql-0368 · Medium mid

Design tables to store prices and payments in several currencies.

Store each amount with its currency code, as an integer of minor units or a NUMERIC, never a float. Record exchange rates in a dated table and, for each transaction, store the rate used and the converted amount in the reporting currency at that time. Remember that currencies differ in minor units, such as 0 for JPY and 3 for some others.

Full answer
text
currencies(code CHAR(3) PK, minor_units)           -- 'INR', 2; 'JPY', 0
fx_rates(base, quote, rate NUMERIC(18,8), as_of DATE, PRIMARY KEY (base, quote, as_of))
payments(id, amount_minor BIGINT, currency CHAR(3) FK, fx_rate_used NUMERIC(18,8),
         amount_reporting_minor BIGINT, paid_at)

Rules:

  • Never add amounts across currencies without converting.
  • Freeze the rate used at transaction time; recalculating with today's rate changes history.
  • Round once, with a documented rule, when converting.
  • Display formatting (symbols, separators) belongs to the presentation layer.

Floats represent many decimal fractions inexactly (0.1 + 0.2 is not 0.3), which is why integer minor units or NUMERIC are used; another item in this bank shows that float result.

Key points

  • Store amount and currency together
  • Integer minor units or NUMERIC, never float
  • Dated exchange-rate table
  • Freeze the rate used per transaction
  • Minor units vary by currency

Common mistakes

  • Summing amounts with different currencies
  • Converting historical data with current rates

Follow-ups

  • How would you report revenue in one currency?
  • Where does rounding happen?

Tips

  • Mention minor units per currency