- 테이블의 각 레코드를 식별
- 중복되지 않은 고유값을 포함
- Null값을 포함할 수 없음
- 테이블 당 하나의 기본키를 가짐
Primary Key는 하나만 설정할 수도 혹은 여러개를 설정할 수도 있다
Create Table tablename
(
column1, data type not null, #Null값을 포함할 수 없으니 Not Null
column2, data type not null,
...
Constraint conatraint_name #constraint는 생략 가능하다
Primary key (column1, column2,....)
);
Alter Table tablename Add Primary Key (column1,column2...)
Primary Key는 각 테이블당 하나의 기본키를 가지므로 한개든 두개든 그냥 Drop하면 된다
Alter Table tablename Drop Primary Key;
- 한 테이블을 다른 테이블과 연결
- 참조되는 테이블의 항목은 그 테이블의 기본키(혹은 단일값)
Create Table tablename
(
column1, data type not null,
column2, data type not null,
...
Constraint conatraint_name
Primary Key (column1, column2,....),
Constraint constraint_name #constriant 생략가능
Foreign Key (colum3, column4,...) References REF_tablename(REF_column)
);
Alter Table tablename
Add Foreign Key (column)
References REF_tablename(REF_columns);
기본키와 달리 외래키는 삭제할 때 이름을 적어줘야 한다
Alter Table tablename Drop Foreign Key constraint_name;
만약 constraint로 이름을 지정하지 않았을 경우, 자동 생성된 이름을 확인하면 됨.
Show create table tablename을 치면 자동생성된 이름을 확인할 수 있음.