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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which objects does the SQL touch?
The references are `ledger`.