1.Numeric Types: smallint, integer, bigint, numeric, real, double precision
smallint, integer and bigint are exact whole numbers of increasing range. numeric (aka decimal) is exact with arbitrary precision, ideal for money. real and double precision are approximate floating-point — fast, but not exact, and wrong for money.
Key features
- smallint: 2 bytes, ±32,767. integer: 4 bytes, ±2.1 billion. bigint: 8 bytes, ±9.2 quintillion
- numeric/decimal stores exact values with user-specified or arbitrary precision — no rounding error
- real (4 bytes) and double precision (8 bytes) are approximate IEEE 754 floating-point
- 0.1 + 0.2 computed in double precision does not equal 0.3 exactly — a floating-point representation artifact, not a PostgreSQL bug
- numeric is slower than integer/real for arithmetic, which is the trade-off for exactness
The numeric type family at a glance
- Exact: integer / bigint / numeric
- represents the written value precisely
- numeric arithmetic never introduces rounding error
- the correct family for money, counts, IDs
- Approximate: real / double precision
- IEEE 754 floating-point — cannot represent most decimals exactly
- 0.1 + 0.2 = 0.30000000000000004 in double precision
- fine for scientific/measurement data, wrong for money
Command
CREATE TABLE accounts (
id BIGINT PRIMARY KEY,
balance NUMERIC(12, 2) NOT NULL,
measurement DOUBLE PRECISION
);integer/bigint/numeric are exact; real/double precision are approximate IEEE 754 floating-point that cannot represent most decimals exactly — never use float types for money.