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

微笑、不失礼 提交于 2019-12-05 03:45:02

问题


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


来源:https://stackoverflow.com/questions/31959145/how-to-count-number-of-digits-in-postgres-integer-data-type

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