- Primary Key : 기본키, null(빈칸)을 허용하지 않는다. 중복을 허용하지 않는다. ex) id, 주민번호
- Unique Key : 고유키, null(빈칸)을 허용한다. 중복을 허용하지 않는다. ex) email
- Foreign Key : 외래키, 테이블과 테이블을 연결하는 목적 성질이다.
Employees(외래키:department_id), Department(기본키:department_id)
외래키로 설정된 컬럼은 primary key나 unique key로 설정되어 있어야 한다.- check : 범위를 지정, 지정된 값외에 null을 사용한다.
- not null : null을 허용하지 않는다. (빈칸을 허용하지 않음)
= unique + not null
create table tb_test1( pkcol varchar2(10) constraints pk_test_01 primary key, col1 varchar2(20), col2 varchar2(20) );
create table tb_test1( ukcol varchar2(10) constraint uk_test_01 unique, col1 varchar2(20), col2 varchar2(20) );
-- check : 지정된 값만 허용. null은 가능 create table tb_check( col1 varchar2(10), col2 varchar2(20), constraint chk_01 check(col1 in ('사과','배', '바나나')), constraint chk_02 check(col2 > 0 and col2 <= 10) ); -- ok insert into tb_check(col1, col2) values('사과', 5); -- ok insert into tb_check(col1) values('배'); -- ok insert into tb_check(col2) values(10); -- check에 위배됨 #1 insert into tb_check(col1, col2) values('포도', 5); -- check에 위배됨 #2 insert into tb_check(col1, col2) values('사과', 15);
create table tb_test01( col1 varchar2(10) not null, col2 varchar2(10) ); insert into tb_test01(col1, col2) values('AAA', '111'); -- col2에는 null이 와도 됨 insert into tb_test01(col1) values('BBB'); -- not null이므로 null을 집어 넣을 수 없음 #1 insert into tb_test01(col2) values('BBB'); -- not null이므로 null을 집어 넣을 수 없음 #2 insert into tb_test01(col1, col2) values('','222');
create table tb_dept( department_id varchar2(10), department_name varchar2(20), location_id number, constraint pk_dept_test primary key(department_id) ); insert into tb_dept(department_id, department_name, location_id) values('10', '기획부', 100); insert into tb_dept(department_id, department_name, location_id) values('20', '영업부', 200); insert into tb_dept(department_id, department_name, location_id) values('30', '개발부', 300);
create table tb_emp( empno varchar2(10), ename varchar2(20), department_idd varchar2(10), constraint fk_emp_test foreign key(department_idd) references tb_dept(department_id) ); insert into tb_emp(empno, ename, department_idd) values (1, '홍길동', '10'); insert into tb_emp(empno, ename, department_idd) values (2, '성춘향', '30'); -- 부모 테이블에 등록된 값이 없음 insert into tb_emp(empno, ename, department_idd) values (3, '홍두께', '40');
유일한 값을 생성해주는 oracle object
-- sequence 생성 create sequence test_seq increment by 1 start with 10 maxvalue 100 minvalue 1; -- currval = 현재의 sequence select test_seq.CURRVAL from dual; -- nextval = 진행 값 select test_seq.NEXTVAL from dual; --수정 alter sequence test_seq increment by 3;
- 사용 예시
create table student( no integer, name varchar2(30), height number(5,1) ); drop table student; insert into student(no, name, height) values (test_seq.nextval, '홍길동', 190.3); insert into student(no, name, height) values (test_seq.nextval, '성춘향', 160.5);