제약조건

제약조건명을 생성할때 규칙을 정하는 것이 좋다

: 테이블명_제약조건약어_적용필드명

기존 테이블에 제약조건 추가하기

Primary key

: 유일한값(unique), 필수입력(not null), 자동 index key 부여

 

alter table test_table add constraint test_table_pk_id primary key(id);
//데이터 추가
SQL> insert into test_table values(1,'김');

//무결성 제약 조건 위배
SQL> insert into test_table values(1,'홍');
*
1행에 오류:
ORA-00001: 무결성 제약 조건(TEST.SYS_C0011134)에 위배됩니다

//데이터 추가
SQL> insert into test_table(id,name) values(2,'홍');

 

Foreign key

: 테이블에 값을 저장하고자 할때 특정 필드와 연결 되어 있는 다른 테이블의 필드값을 검사(존재 체크)

한 후, 값을 저장 시켜준다.

alter table 테이블1 add constraint 제약조건명 foreign key(테이블1의 필드명)
references 테이블2(필드명)

 

Unique

: 유일한값(unique)

alter table test_table add constraint test_table_uk_id unique(id);

 

Check

: 데이터를 저장시킬때 올바른 값이 들어왔는지를 체크

(숫자->범위지정 / 문자->올바른 값만 미리 등록 등...)

alter table test_table add constraint test_table_ck_age 
check (age>=20 and age<=65);

alter table test_table add constraint test_table_ck_job 
check (job in ('MANAGER','ANALYST'));

 

기존 테이블에서 제약조건 삭제하기

alter table test_table drop constraint test_table_pk_id;

 


테이블 이름 변경

rename 변경전테이블명 to 변경후테이블명;

 

+ Recent posts