numeric
Learning Focus
Use this lesson to choose PostgreSQL numeric(p,s) for exact values and avoid floating-point rounding in financial calculations.
numeric Overview
- Exact, arbitrary precision (within configured precision)
- Use
numeric(p,s)to set precision and scale (e.g.,numeric(12,2)) - Best for: money-like values, measurements requiring exact decimals
Example
CREATE TABLE invoices (
invoice_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
amount numeric(12,2) NOT NULL CHECK (amount >= 0)
);
Performance Notes
numericis slower than integer arithmetic.- For very high volume payments, some systems store cents as
bigintand format in the application.
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
| Using float types for money | Rounding errors | Use numeric(p,s) |