NUMERIC Precision Scale Rounds On Insert
A numeric(8,2) column rounds 123.456 to 123.46 on insert, while a value that no longer fits the declared precision raises a field-overflow error.
Code
-- numeric(precision, scale):写入按 scale 舍入,整数位超出 precision 报错
CREATE TABLE ledger (
entry_id int GENERATED ALWAYS AS IDENTITY,
amount numeric(8, 2) -- 共 8 位:小数 2 位,整数最多 6 位
);
INSERT INTO ledger (amount) VALUES (123.456); -- 舍入成 123.46 后存入
SELECT amount FROM ledger; -- 123.46
-- 整数部分超过 6 位:拒绝写入,SQLSTATE 22003
DO $$
BEGIN
INSERT INTO ledger (amount) VALUES (1234567.89);
EXCEPTION
WHEN numeric_value_out_of_range THEN
RAISE NOTICE 'rejected: value exceeds numeric(8,2) precision';
END $$;How the snippet works
The file runs SELECT / INSERT / CREATE statements, touching ledger.
Breaking the statements into their working parts: a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
The ledger table is the working surface here.
Statements that move the data
DO $$
BEGIN
INSERT INTO ledger (amount) VALUES (1234567.89);
EXCEPTION
WHEN numeric_value_out_of_range THEN
RAISE NOTICE 'rejected: value exceeds numeric(8,2) precision';
END $$;
CREATE TABLE ledger (
entry_id int GENERATED ALWAYS AS IDENTITY,
amount numeric(8, 2) -- 共 8 位:小数 2 位,整数最多 6 位
);
INSERT INTO ledger (amount) VALUES (123.456); -- 舍入成 123.46 后存入
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
- Which objects does the SQL touch?
- The references are `ledger`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.