How to count number of digits in Postgres integer data type?

荒凉一梦 提交于 2019-12-03 20:57:27

Have a check constraint with

check (value>99999 and value<=9999999)

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!