How to count number of digits in Postgres integer

2019-04-02 08:36发布

问题:

I need to restrict the number of digits in the 'integer' type fields to 6 or 7 in postgres.

Basically it should accept 123456 or 1234567 but it should not accept 12345 or 12345678. How can I achieve this??

回答1:

Have a check constraint with

check (value>99999 and value<=9999999)


回答2:

You can use floor(log(i)+1 to get the number of digits in a number (that's base10 log).

DB> CREATE TEMP TABLE t (
      i integer CONSTRAINT i_has_6_or_7_digits CHECK (floor(log(abs(i))+1) BETWEEN 6 AND 7)
    );
CREATE TABLE
Time: 5,676 ms

DB> INSERT INTO t VALUES (123456), (1234567);
INSERT 0 2
Time: 0,471 ms

DB> INSERT INTO t VALUES (12345);
ERROR:  23514: new row for relation "t" violates check constraint "i_has_6_or_7_digits"
DETAIL:  Failing row contains (12345).
SCHEMA NAME:  pg_temp_2
TABLE NAME:  t
CONSTRAINT NAME:  i_has_6_or_7_digits
LOCATION:  ExecConstraints, execMain.c:1661
Time: 0,468 ms

DB> INSERT INTO t VALUES (12345678);
ERROR:  23514: new row for relation "t" violates check constraint "i_has_6_or_7_digits"
DETAIL:  Failing row contains (12345678).
SCHEMA NAME:  pg_temp_2
TABLE NAME:  t
CONSTRAINT NAME:  i_has_6_or_7_digits
LOCATION:  ExecConstraints, execMain.c:1661
Time: 0,215 ms