Postgresql – How to prevent PostgreSQL from automatically rounding numeric types

decimalpostgresql

I have a simple schema and query for a MWE.

Schema:

CREATE TABLE ttable (
  tcol Numeric(19,4)
)

Query:

INSERT INTO ttable (tcol) VALUES ('123.45678');
SELECT * FROM ttable;

Fiddle

Result:

123.4568

In this case, I have lost precision. I entered five decimal places, but Postgres automatically rounded down to four. I want this to be an error, or at least a warning of some kind that I can detect, so that I can tell the user about the loss of precision.

How can I make this happen?

Edit:

This question is obviously not a duplicate of this question. In that question, the user is using a client application which is rounding value below the stored precision. My question is about Postgres itself rounding the data to fit, not the client displaying. This would be obvious to anyone who looked further than the title of both questions.

Best Answer

I want this to be an error

You could use a check constraint that validates the scale of the value, rather than the definition of the data type:

CREATE TABLE ttable 
(
  tcol numeric,
  constraint check_tcol_scale check (scale(tcol) <= 4)
);

Note also that the column itself needs to be redefined as just numeric, rather than numeric(19,4).

Then the following:

insert into ttable values (123.45678);

will result in

ERROR: new row for relation "ttable" violates check constraint "check_tcol_scale"
   Detail: Failing row contains (123.45678)

But

insert into ttable values (123.4567);

will succeed.

Check out this fiddle to see this solution in action.