본 글은 아사이 아츠시 저 '하루 30분 36강으로 배우는 완전 초보의 SQL 따라잡기 SQL 첫걸음'을 기반으로 작성되었습니다.
create table {name} (col1, col2, ...)
열을 정의할 때 열명, 자료형, 기본값, NOT NULL 제약 등을 정의할 수 있다.
create table sample62 (
no integer not null,
a varchar(30),
b date
);
drop table {table_name}
truncate table {table_name}
delete from {table_name}
과 결과는 같지만 속도에서 truncate
명령어가 우세하다.
새로운 열의 이름, 자료형, 기본값과 NOT NULL 등을 추가할 수 있다.
alter table {table_name} add {col};
alter table sample62 add newcol integer;
modify
명령어를 통해 기존의 열의 속성(자료형, 기본값, NOT NULL 등)을 수정할 수 있다.
단, 기존의 열의 이름은 change
명령어를 사용해야 한다. change
명령어의 경우, 열 이름 변경 및 속성 변경이 모두 가능하다.
alter table sample62 modify newcol varchar(20) default "empty" NOT NULL;
alter table sample62 change newcol c varchar(20);
alter table sample62 drop c
create table sample631 (
a integer not null,
b integer not null, unique
c varchar(30)
);
create table sample632(
no integer not null,
sub_no integer not null,
name varchar(30),
primary key(no, sub_no)
);
primary key(a,b)
와 같이 한 개의 제약으로 복수의 열에 제약을 설명하는 경우를 '테이블 제약'이라고 부른다.
alter table sample631 modify c varchar(30) not null;
alter table sample631 add constraint pkey_sample631 primary key(a);
alter table sample631 modify c varchar(30); // not null 제약 삭제
alter table sample631 drop primary key; // pk 제약 삭제
create table sample634(
p integer not null,
a varchar(30),
constraint pkey_sample634 primary key(p) // pk 제약 추가 및 제약에 이름 부여
);
주의할 점
pk로 지정할 열은 not null 제약이 설정되어 있어야 함.
pk로 지정된 열은 insert, update 등의 데이터 수정에서 중복된 값을 가질 수 없음.
복수의 열이 pk로 지정되어 있을 시, 모든 열의 값이 다 같아야 중복으로 인정.