How to Store Exchange Rates in a Database: Column Types and Schema
6 min read
If you need to store exchange rates in a database, use an exact decimal type (NUMERIC in PostgreSQL, DECIMAL in MySQL), never FLOAT or DOUBLE. Keep the rate exactly as the API returned it, and store it together with the pair, the observation time and a few status fields. Store money amounts as integers in minor units or as exact decimals, and do the rounding once, at the end.
That one-sentence answer hides a few decisions that cause real bugs later: how many digits to allow, what to do with crypto rates that have many decimals, which timestamps to keep, and whether a rate belongs in its own table. This article walks through each one and ends with a schema you can copy.
Why FLOAT is the wrong column type for exchange rates
A binary float cannot represent most decimal fractions exactly. A rate like 1.0842 is stored as the closest binary value, and the error shows up when you multiply it by an amount and compare totals. It may be tiny, but accounting systems compare totals to the cent, and a one-cent difference between your database and your invoice PDF is a support ticket.
The error can also arrive before the database sees anything. If your code parses the JSON rate into a float and then inserts it, the damage is already done. GetRatesAPI returns rates and amounts as JSON strings for this reason, and does not round results. Keep them as strings or decimal objects all the way to the INSERT. For the application side of this, see Currency Conversion Rounding: How to Convert Money Without Floating-Point Errors.
Choosing precision and scale for a rate column
Fixed precision, such as NUMERIC(12,6), is tempting but risky. Rates span a huge range:
- A major pair like EUR/USD needs about four to six decimals.
- A pair like USD/JPY has a large integer part.
- A crypto price quoted in a currency like USD might be
0.00000841for a tiny token, while the inverse (tokens per dollar) is a large number with decimals. - A derived rate multiplies or divides inputs, which adds digits.
If the column cannot hold what the API sends, either the insert fails or the database silently rounds, depending on your settings. Neither is what you want from a record you may need to defend in an audit.
Practical choices:
| Database | Suggested type | Notes |
|---|---|---|
| PostgreSQL | NUMERIC (no precision) | Arbitrary precision. Simplest and safe. |
| MySQL / MariaDB | DECIMAL(40,20) | Maximum scale is 30 in MySQL; 20 decimals covers crypto-quoted pairs. |
| SQL Server | DECIMAL(38,18) | Maximum precision is 38. |
| SQLite | TEXT | SQLite has no exact decimal type. Store the string and parse in code. |
Whatever you pick, test it with the smallest and largest values you expect, including a tiny crypto price. For more on tiny prices, see Crypto Decimal Precision: Handling Satoshis, Wei and Tiny Prices Without Float Errors.
What to store alongside the rate
A bare number is not a useful record. Months later, someone will ask which rate was used and whether it was trustworthy. The API gives you the answers in each response, so keep them:
baseandquote: the pair, with the direction defined. The rate means "1 base = rate quote".rate: the exact string, as a decimal.as_of: the time of the observation, not the time you fetched it.fetched_at: when your system received it. The gap between the two is useful when debugging.status:freshorstale.type:directorderived. For a derived rate,as_ofis the oldest input.
Do not store the inverse rate as a second column. Compute it when needed, and keep one source of truth. The inverse exchange rate guide explains why.
A working PostgreSQL schema
Here is a minimal design with a snapshot table and a payments table that points at it.
CREATE TABLE fx_rate_snapshots (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
base varchar(16) NOT NULL,
quote varchar(16) NOT NULL,
rate numeric NOT NULL CHECK (rate > 0),
as_of timestamptz NOT NULL,
fetched_at timestamptz NOT NULL DEFAULT now(),
status text NOT NULL CHECK (status IN ('fresh', 'stale')),
rate_type text NOT NULL CHECK (rate_type IN ('direct', 'derived'))
);
CREATE INDEX fx_rate_snapshots_lookup
ON fx_rate_snapshots (base, quote, as_of DESC);
CREATE TABLE payments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
amount_minor bigint NOT NULL,
currency varchar(16) NOT NULL,
settled_minor bigint,
settled_currency varchar(16),
rate_snapshot_id bigint REFERENCES fx_rate_snapshots (id)
);
Some notes on the choices:
- Code columns are
varchar(16)rather thanchar(3)because crypto asset codes can be longer than three characters. Validate codes in your application; the currency code validation article covers how. amount_minorholds integer minor units, such as cents. Abigintavoids decimals entirely for money. Note that minor units differ by currency: JPY has none, KWD has three. See Currency Decimal Places.- Each payment references the exact snapshot it used. Nothing is overwritten, so a later refund or audit can find the original rate. The foreign currency refund guide explains when you reuse that rate.
The API serves current rates only. It is not a history service, so a table like this is how you keep your own record of the rates you actually used.
Inserting a rate without losing digits
Fetch the rate, parse the string into a decimal and pass it to a parameterized query. This Python example uses requests and psycopg, with the key read from an environment variable.
import os
from datetime import datetime
from decimal import Decimal
import psycopg
import requests
API = "https://api.getratesapi.com"
HEADERS = {"Authorization": f"ApiKey {os.environ['GETRATESAPI_KEY']}"}
def snapshot_rate(conn, base: str, quote: str) -> int:
resp = requests.get(f"{API}/v1/rates/{base}/{quote}", headers=HEADERS, timeout=10)
resp.raise_for_status()
data = resp.json()
row = conn.execute(
"""
INSERT INTO fx_rate_snapshots (base, quote, rate, as_of, status, rate_type)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING id
""",
(
data["base"],
data["quote"],
Decimal(data["rate"]), # string -> Decimal, never float
datetime.fromisoformat(data["as_of"].replace("Z", "+00:00")),
data["status"],
data["type"],
),
).fetchone()
conn.commit()
return row[0]
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
print(snapshot_rate(conn, "EUR", "USD"))
Details of the request and response are in the current rate documentation. If a call fails, match on the error code, as described in Exchange Rate API Error Handling.
Decide what to do with "status": "stale" before you write code. For a quote shown to a customer you may refuse it; for an internal report you may store it and flag it. Because the status is a column, you can always find those rows later.
Watch your driver as well. Some libraries return NUMERIC columns as floats by default. The pg package for Node returns them as strings, which is safe, but check your own stack, and read decimals into a decimal type.
Converting inside the database
Sometimes you want a report without pulling rows into application code. Exact decimals make this safe, as long as you round once at the end.
SELECT
p.id,
p.amount_minor AS eur_cents,
round(p.amount_minor * s.rate) AS usd_cents
FROM payments p
JOIN fx_rate_snapshots s ON s.id = p.rate_snapshot_id
WHERE p.currency = 'EUR'
AND s.base = 'EUR'
AND s.quote = 'USD';
With the example rate 1.0842 and an amount of 12550 cents, the product is 13606.71, which rounds to 13607 cents. This works directly because both EUR and USD have two decimal places. When the minor-unit exponents differ, such as EUR to JPY, scale by the power of ten that matches the difference before rounding.
Note that round() on numeric rounds half away from zero in PostgreSQL. If your finance team requires another rule, such as banker's rounding, apply it in code or in an explicit function, and document it.
Pitfalls to avoid
- Overwriting a rate row. Insert new snapshots; never update old ones. A payment's rate must stay fixed.
- Using
fetched_atas the rate time. The observation time isas_of. Use it for freshness checks. - Storing every poll. Snapshot at business events, such as an order, an invoice or a month-end close, rather than every few seconds. This also keeps request usage low. For month-end work, see Foreign Currency Revaluation.
- Rounding before storing. Keep the full rate. Round the converted amount, not the rate.
- Mixing directions. Always define the rate as
1 base = rate quoteand name the columns accordingly.
Start with a real rate
You can create a free account, with no credit card, at app.getratesapi.com/signup and try the endpoints in the dashboard playground. Fetch EUR/USD, insert it into the schema above and check that the digits come back identical. The pricing page lists plans if your snapshot volume grows.