기존 생성된 테이블에 제약조건(Primary key 추가, 삭제 등) 추가할 때 사용
Primary Key 추가(괄호 주의)
alter table 테이블명 add constraint primary key (컬럼명);
Primary Key 삭제(괄호 주의, not null 별도 해제 필요)
alter table 테이블명 drop primary key;
not null 설정(자료형 명시 중요)
alter table 테이블명 modify 컬럼명 자료형() not null;
not null 해제(자료형 명시 중요)
alter table 테이블명 modify 컬럼명 자료형();
unique 설정(괄호 주의)
alter table 테이블명 add constraint unique (컬럼명);
unique 해제
alter table 테이블명 drop constraint 제약조건명(unique로 지정된 행의 이름)
foregin key 설정
alter table 테이블명 add foreign key(컬럼명) references 참조테이블명(참조컬럼명)
foreign key 해제 1/2
desc를 통해 확인 시 잔재가 남아 있으므로, 아래 방식을 통해 확실하게 해제 해야함. 제약조건명은 더보기를 통해서 확인
alter table 테이블명 drop foreign key 제약조건명(foreign key로 지정된 행의 이름)
더보기

select constraint_name, table_schema, table_name, constraint_type
from information_schema.table_constraints
where constraint_schema='데이터베이스명';

foreign key 해제 2/2
alter table 테이블명 drop index 컬럼명;
Primary Key 지정 1
create table 테이블명 (
컬럼명 자료형(크기) primary key,
컬럼명 자료형(크기),
...
)
더보기
create table emp01 (
empno int(4) primary key,
ename varchar(10)
);
Primary Key 지정 2(묶음, 중복 지정 가능)
create table 테이블명 (
컬럼명 자료형(크기),
컬럼명 자료형(크기),
...
constraint primary key (컬럼명, 복수개 가능)
)
더보기
create table emp01 (
empno int(4),
ename varchar(10),
constraint primary key (empno, ename)
);
Primary Key + auto_increment 지정
create table 테이블명 (
컬럼명 자료형(크기) primary key auto_increment,
컬럼명 자료형(크기),
...
)
더보기
create table dept_a1 (
deptno int(2) primary key auto_increment,
dname varchar(14),
loc varchar(13)
);
Primary Key + unsigned + auto_increment 지정
create table 테이블명 (
컬럼명 자료형(크기) unsigned primary key auto_increment,
컬럼명 자료형(크기),
...
)
더보기
create table dept_a2 (
deptno int(2) unsigned primary key auto_increment,
dname varchar(14),
loc varchar(13)
);
Foreign Key 지정
create table 테이블명 (
컬럼이름 자료형(크기),
컬럼이름 자료형(크기),
...
constraint foreign key (컬럼명) references 참조테이블명 (침조컬럼명)
)
더보기
create table dept02 (
empno int(4),
constraint foreign key (empno) references emp01 (empno)
);