Sub topic 3
Exact decimals with `numeric`
Assume you know basic SELECT expressions and can create tables. This chapter focuses on PostgreSQL's numeric type for values where decimal accuracy matters, such as prices, tax rates, measurements, and account balances.
What `numeric` stores
numeric is an exact decimal type. PostgreSQL stores the decimal value rather than an approximation based on binary floating-point arithmetic.
You can declare numeric without limits:
CREATE TABLE measurements (
reading numeric
);You can also specify precision and scale:
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
subtotal numeric(12,2) NOT NULL CHECK (subtotal >= 0),
tax_rate numeric(5,4) NOT NULL CHECK (tax_rate >= 0),
total numeric(12,2) NOT NULL CHECK (total >= 0)
);In numeric(12,2), the precision is 12, the maximum number of decimal digits in the whole value. The scale is 2, the number of digits allowed after the decimal point. Therefore, the largest ordinary positive value is 9999999999.99.
PostgreSQL rounds a value to the declared scale when it stores it. A value that still has too many digits before the decimal point after rounding causes an error.
INSERT INTO invoices (subtotal, tax_rate, total)
VALUES (19.995, 0.0825, 21.64);
SELECT subtotal, tax_rate
FROM invoices;The subtotal value is stored at two decimal places, so it is rounded according to PostgreSQL's numeric rules. Choose the scale to match the business rule, rather than relying on accidental rounding during insertion.
Why not use floating point for money?
real and double precision use binary floating-point representations. They are useful for scientific or approximate calculations, but many decimal fractions cannot be represented exactly in binary.
SELECT
0.1::double precision + 0.2::double precision = 0.3::double precision
AS float_equal,
0.1::numeric + 0.2::numeric = 0.3::numeric
AS numeric_equal;The floating-point comparison can return false, while the numeric comparison returns true. For currency, store the amount as numeric, and define its scale explicitly. For example, numeric(12,2) supports cents. For rates that need four decimal places, use a suitable scale such as numeric(8,4).
Do not choose an unnecessarily small precision. A column defined as numeric(5,2) cannot store 12345.67, because that value has seven total digits.
Exercise
Which type would you choose for a product price that must support values up to 9,999,999.99, and why?
Show answer
Use numeric(10,2). It allows eight digits before the decimal point and two after it, for ten total digits, and stores the price as an exact decimal.