1. CREATE (테이블 생성)
primary key는 중복된 값이 들어 올 수 없고, null을 허용하지 않는다.
unique는 중복된 값이 들어 올 수 없지만, null은 허용한다.
-- 1. create table (생성)
create table team_tb (
변수명 타입,
); -- 기본문법;
create table team_tb (
tno int primary key, -- tno은 중복 안됨(unique), null 허용 x
tname varchar(10) unique, -- tname도 중복 안됨, null 허용 o
tyear int,
tloc varchar(10)
) charset=utf8mb4;
2. ALTER (테이블 수정)
테이블을 수정하는 문법이다. 문법을 사용할 수도 있지만, workbench에서 직접 변경도 가능하다.

-- 2. alter table (수정)
alter table 테이블명 change column 기존컬럼명 바꿀컬럼명 타입; -- 기본문법
alter table player_tb change column prole ptype varchar(20);
3. DROP (테이블 삭제)
테이블을 삭제 해주는 문법
-- 3. drop table (삭제)
drop table 테이블명;
drop table player_tb;
4. TRUNCATE (테이블 초기화)
삭제와는 다르게 TRUNCATE는 테이블 안에 있는 데이터를 초기화 하는 문법이다.
-- 4. truncate (데이터 초기화)
truncate 테이블명;
truncate team_tb;
5. 제약조건들
MySQL의 제약조건들
제약조건 | 설명 |
AUTO_INCREMENT | 숫자 값을 자동 증가 (보통 PRIMARY KEY 와 함께 사용) |
NOT NULL | 컬럼이 NULL 값을 가질 수 없도록 제한 |
DEFAULT | 값을 입력하지 않으면 기본값을 자동 설정 |
PRIMARY KEY | NOT NULL + UNIQUE , 테이블에서 각 행을 고유하게 식별 |
FOREIGN KEY | 다른 테이블의 PRIMARY KEY 를 참조하여 관계를 형성 |
UNIQUE | 해당 컬럼의 값이 중복되지 않도록 제한 |
CHECK | 특정 조건을 만족하는 값만 허용 (MySQL 8.0 이상 지원) |
제약조건들은 엄청 많지만 3개를 사용해봤다.
- Auto_increment
- not null
- default
-- 5. 제약조건들
create table player_tb (
pno int primary key auto_increment,
pname varchar(20) not null,
pnumber int,
prole varchar(10) default '타자',
tno int
) charset=utf8mb4;
6. FK 제약조건
-- 3 fk 제약조건으로 인해 isert불가능
insert into player_tb(pname, pnumber, prole, tno) values('홍길동', 19, '1루수', 4);
-- 4 삭제 (성공)
delete from player_tb where pno = 5;
-- 5 삭제 (실패)
-- (1) 참조하고 있는 이승엽의 tno를 null로 업데이트 후 삭제하면 삭제됨
-- (2) cascade
delete from team_tb where tno = 1;
-- 6. cascade
drop table if exists team_tb; -- 존재하면 삭제 없으면 냅둠
drop table if exists player_tb;
select *
from player_tb;
desc player_tb;
-- 모든 제약조건 잠시 해제 후 테이블 삭제
drop table if exists team_tb;
drop table if exists player_tb;
-- cascade : on delete (위험)
create table player_tb (
pno int primary key auto_increment,
pname varchar(20) not null,
pnumber int,
prole varchar(10) default '타자',
tno int,
-- 외래키 설정 : 제약 조건 (참조할 테이블에 없는 값이 안들어가도록) / constraint 이름 foreign key(column) references 참조할 테이블(column)
constraint fk_player_tb foreign key(tno) references team_tb(tno)
on delete cascade
) charset=utf8mb4;
delete from team_tb where tno = 3;
select *
from player_tb;
-- cascade : on delete set null (삭제하면 값 null로 변경)
create table player_tb (
pno int primary key auto_increment,
pname varchar(20) not null,
pnumber int,
prole varchar(10) default '타자',
tno int,
-- 외래키 설정 : 제약 조건 (참조할 테이블에 없는 값이 안들어가도록) / constraint 이름 foreign key(column) references 참조할 테이블(column)
constraint fk_player_tb foreign key(tno) references team_tb(tno)
on delete set null
) charset=utf8mb4;

Share article