Sobes.tech
Senior

What data types in PostgreSQL are suitable for storing money?

sobes.tech AI

Answer from AI

To store monetary values in PostgreSQL, data types with fixed precision are usually used to avoid rounding errors characteristic of floating-point numbers. The main options are:

  • numeric(precision, scale) — the most versatile and recommended type for money. It allows setting precision and the number of decimal places. For example, numeric(15,2) stores numbers with 2 decimal places.

  • money — a specialized type for money, which stores values with fixed precision and is formatted considering the locale. However, it has limitations: it depends on the locale, is not always convenient for complex calculations, and is not always portable between different DBMSs.

Example of using numeric:

CREATE TABLE transactions (
  id serial PRIMARY KEY,
  amount numeric(15,2) NOT NULL
);

It is recommended to use numeric as it is more flexible and precise for financial calculations.