/* primary key */
CREATE TABLE primary_test(
student_id number(10) PRIMARY KEY,
name varchar2(20)
);
SELECT * FROM PRIMARY_TEST
CREATE TABLE primary_test2(
student_id number(10),
name varchar2(20),
CONSTRAINTS student_pk PRIMARY key(student_id)
);
SELECT * FROM PRIMARY_TEST2;
1)
create table pkTest(
pkCol1 varchar2(10) primary key
);
2)
create table pkTest(
pkCol1 varchar2(10) primary key constraints pk이름 primary key
);
3)
create table pkTest(
pkCol1 varchar2(10),
pkCol2 varchar2(10),
pkCol3 varchar2(10),
constraints pk이름 primary key(pkCol1)
);
/* foreign key */
CREATE TABLE daddy(
idx number(10),
mID number(10) PRIMARY key
);
CREATE TABLE daughter(
idx number(10) PRIMARY KEY,
mID number(10),
CONSTRAINTS fk_daddy FOREIGN KEY (mID)
REFERENCES daddy(mID) ON DELETE CASCADE
);
SELECT * FROM DADDY d ;
INSERT INTO daddy VALUES (1, 10);
INSERT INTO daddy VALUES (2, 20);
INSERT INTO daddy VALUES (3, 30);
DELETE FROM DADDY WHERE idx = 2;
/*
IDX MID
1 10
2 20
*/
SELECT * FROM DAUGHTER d ;
INSERT INTO DAUGHTER VALUES (100, 10);
INSERT INTO DAUGHTER VALUES (101, 10);
INSERT INTO DAUGHTER VALUES (102, 10);
INSERT INTO DAUGHTER VALUES (200, 20);
INSERT INTO DAUGHTER VALUES (201, 20);
INSERT INTO DAUGHTER VALUES (202, 20);
INSERT INTO DAUGHTER VALUES (300, 30);
INSERT INTO DAUGHTER VALUES (301, 30);
INSERT INTO DAUGHTER VALUES (302, 30);
1)
create table fk_test(
department_id varchar2(10)
constraints fk이름 references departments(departments_id)
);
2)
create table fk_test(
department_id varchar2(10),
...
constraints dept_fk foreign key(department_id)
references departments (department_id)
);
ON DELETE CASCADE
-> 참조되는 부모 테이블의 해에 대한 delete를 허용한다.
즉, 참조되는 부모 테이블 값이 삭제되면 연쇄적으로 자식 테이블 값 역시 삭제된다.
-> 보통 많이 사용
ON DELETE SET NULL
-> 참조되는 부모 테이블의 해에 대한 delete를 허용한다.
즉, 부모 테이블 값이 삭제가 되면 해당 참조하는 자식 테이블의 값들은 NULL값으로 설정된다.
CREATE TABLE daddy2(
idx number(10),
mID number(10) PRIMARY key
);
CREATE TABLE daughter2(
idx number(10) PRIMARY KEY,
mID number(10),
CONSTRAINTS fk_daddy2 FOREIGN KEY (mID)
REFERENCES daddy2(mID) ON DELETE SET null
);
SELECT * FROM DADDY2 d ;
INSERT INTO DADDY2 VALUES (1, 10);
INSERT INTO DADDY2 VALUES (2, 20);
INSERT INTO DADDY2 VALUES (3, 30);
DELETE FROM DADDY2 WHERE idx = 2;
SELECT * FROM DAUGHTER2 d ;
INSERT INTO DAUGHTER2 VALUES (100, 10);
INSERT INTO DAUGHTER2 VALUES (101, 10);
INSERT INTO DAUGHTER2 VALUES (102, 10);
INSERT INTO DAUGHTER2 VALUES (200, 20);
INSERT INTO DAUGHTER2 VALUES (201, 20);
INSERT INTO DAUGHTER2 VALUES (202, 20);
INSERT INTO DAUGHTER2 VALUES (300, 30);
INSERT INTO DAUGHTER2 VALUES (301, 30);
INSERT INTO DAUGHTER2 VALUES (302, 30);
CREATE TABLE UNIQUE_TEST2 (
col1 varchar2(20),
col2 varchar2(20),
CONSTRAINTS temp_unique2 unique(col1, col2)
);
SELECT * FROM UNIQUE_TEST2;
INSERT INTO UNIQUE_TEST2 (col1, col2)
VALUES ('aa','tt');
SELECT * FROM UNIQUE_TEST2;
많은 도움이 되었습니다, 감사합니다.