Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 and only 2 characters for oracle table

Tags:

oracle

I am trying to create a table in oracle that will accept 2 and only 2 characters. I tried using char(2), but if I put in 1 character in an insert statement, it will accept it. How do I make oracle only accept any inserts of 2 exact characters and reject 1 and 3 and higher characters? I have searched all over the internet and can't seem to find an answer for this.

Thanks! Christopher

like image 904
Christopher Avatar asked Dec 22 '22 12:12

Christopher


1 Answers

You can create a CHECK constraint that enforces this restriction

SQL> create table foo (
  2    col1 varchar2(2) NOT NULL
  3   ,check( length(col1) = 2 )
  4  );

Table created.

SQL> insert into foo values( 'ab' );

1 row created.

SQL> ed
Wrote file afiedt.buf

  1* insert into foo values( 'a' )
SQL> /
insert into foo values( 'a' )
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C0022134) violated
like image 155
Justin Cave Avatar answered Jan 29 '23 12:01

Justin Cave