money Type Stores Exact Cents
Use the money type for currency that stays exact through addition and SUM, while division by an integer truncates and numeric mixes need casts.
Code
CREATE TABLE ledger_lines (
id int PRIMARY KEY,
label text NOT NULL,
amount money NOT NULL
);
INSERT INTO ledger_lines VALUES
(1, 'subscription', 12.34::money),
(2, 'addon', 5.67::money);
-- money 的加法与 SUM 保持分币精确,没有二进制浮点漂移
SELECT SUM(amount) AS total FROM ledger_lines;
-- money ÷ 整数:小数部分向零截断(12.34 / 7 → 1.76,不是四舍五入)
SELECT amount / 7 AS divided FROM ledger_lines WHERE id = 1;
-- money ÷ money:币种单位相消,结果是 double precision 的纯比率
SELECT amount / '12.34'::money AS ratio FROM ledger_lines WHERE id = 1;
-- 与 numeric 混算必须显式转换;money → numeric 转换无精度损失
SELECT amount::numeric * 1.5 AS half_up FROM ledger_lines WHERE id = 1;
-- 输出格式由 lc_monetary 决定:同样的值在不同 locale 下渲染不同
SELECT amount, amount::text AS rendered FROM ledger_lines ORDER BY id;How it works
What runs here is SELECT / INSERT / CREATE — ledger_lines are the objects involved.
The pieces that do the work: a WHERE clause limiting a statement to the rows that qualify; SUM aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The ledger_lines table is the working surface here.
Statements that matter
SELECT amount / '12.34'::money AS ratio FROM ledger_lines WHERE id = 1;
SELECT amount::numeric * 1.5 AS half_up FROM ledger_lines WHERE id = 1;
SELECT amount / 7 AS divided FROM ledger_lines WHERE id = 1;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `ledger_lines` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.