-5

I have a string column, which stores numbers. How can I add a constraint to make sure that the number consists of only 6 or 7. Example 676666 But I do not want 565677

Utsav
  • 7,914
  • 2
  • 17
  • 38
nostress
  • 13
  • 6

3 Answers3

4

Add a check constraint:

CONSTRAINT check_numbers CHECK (regexp_like(the_column, '^[67]+$')) 

This requires at last one digit.

1

Add this constraint. I didn't run it but please try

CONSTRAINT CHECK_6_7_ONLY CHECK (regexp_replace(trim(column_name),'6|7','') is null)

Edit: Added trim as we are dealing with strings

Utsav
  • 7,914
  • 2
  • 17
  • 38
1

Another option is to use translate:

create table t42 (
  foo varchar2(10),
  constraint sixesorsevens check (translate(foo, 'x67', 'x') is null)
);

Table T42 created.

insert into t42 (foo) values (null);

1 row inserted.

SQL> insert into t42 (foo) values ('676666');

1 row inserted.

SQL> insert into t42 (foo) values ('576666');

insert into t42 (foo) values ('576666')
*
ERROR at line 1:
ORA-02290: check constraint (MYSCHEMA.SIXESORSEVENS) violated

... but the regexp_like() version might be clearer to someone who has to maintain this.

Alex Poole
  • 183,384
  • 11
  • 179
  • 318