DB의 민족/MYSQL
< MySQL DDL(데이터 정의어) >
댕구리댕댕구리
2022. 4. 5. 15:23
728x90
반응형
SMALL
city 테이블과 똑같은 테이블 생성
create table city2 as select * from city;
select * from city2;
database를 생성 / 사용
create database dangguri;
use dangguri;
CREATE 구문을 활용한 테이블 생성
- (컬럼이름, 형식, not null/null, 키 설정)
create table test2 (
id int not null primary key,
col1 int null,
col2 float null,
col3 varchar(45) null );
ALTER TABLE과 함께 ADD를 사용하면 테이블에 컬럼 추가
ALTER table test2
ADD col4 int null;
select * from test2;
형식을 수정하는 경우에는 MODIFY 사용
ALTER table test2
MODIFY col4 varchar(20);
desc test2;
DROP : 삭제
ALTER table test2
DROP col4;
DESC test2;
인덱스(INDEX)
- 원하는 데이터를 빠르게 탐색
- 검색과 질의를 할 경우 테이블 전체를 읽지 않아 빠름
- 삽입, 삭제, 수정 작업이 원본 테이블에서 이뤄질 경우, 인덱스도 함께 수정
인덱스 생성 및 확인
create index col1Idx
on test2 (col1);
# 인덱스 정보 보기
show index from test2;
CREATE UNIQUE INDEX : 중복 값을 허용하지 않는 인덱스 생성
create index col2Idx
on test2 (col2);
# 인덱스 정보 보기
show index from test2;
FULLTEXT INDEX : 매우 빠르게 테이블의 모든 텍스트 컬럼을 조사
alter table test2
add fulltext col3Idx(col3);
show index from test2;
INDEX 삭제
alter table test2
drop index col3Idx;
show index from test2;
뷰(VIEW)
- DATABASE에 존재하는 가상의 테이블 (실제로 테이블처럼 행과 열은 존재하나 저장을 안함)
- MySQL에서는 뷰에 저장되어 있는 데이터만 보여줌
- 장점
- 특정 사용자에게 필요한 컬럼만 공개 가능
- 복잡한 쿼리 단순화
- 쿼리 재사용 가능
- 단점
- 한 번 정의한 VIEW는 변경 불가
- 삽입/삭제/갱신 작업에 많은 제한 사항 존재
- 자신만의 인덱스 소유 불가
create view testview as
select col1, col2
from test2;
select * from testview;
VIEW 수정
alter view testview as
select col1, col2, col3
from test2;
select * from testview;
VIEW 삭제
drop view testview;
INSERT
- 테이블 이름 다음에 나오는 열 생략
- 생략할 경우 VALUE 다음에 나오는 값 들의 순서 및 개수가 테이블에 있는 것과 동일해야함
insert into test
value(1, 123, 1.1, 'Test');
insert into test
value(2, 234, 2.2, 'Test');
insert into test
value(3, 345, 3.3, 'Test');
UPDATE SET
update test
set col1 = 1, col2 = 1.0, col3 = 'test'
where id = 1;
DELETE
- 행 단위로 데이터를 삭제
- DELETE FROM 테이블 이름 WHERE 조건
- 데이터는 지워지지만, 용량의 변화는 없음
- 삭제 후 복원 가능
delete from test
where id =1;
select * from test;
TRUNCATE
- 용량이 줄어들고, 인덱스 등 모두 삭제
- 테이블은 남기고 데이터만 삭제
- 삭제 후 복원 불가능
truncate table test;
마무리 삭제
# drop table
drop table test;
select * from test;
# drop database
drop database dangguri;
728x90
반응형
LIST