데이터정의언어 (DDL: Data Definition Language)
: CREATE, ALTER, DROP 등의명령어
zerobase 라는이름의데이터베이스생성
CREATE DATABASE zerobase DEFAULT CHARACTER SET utf8mb4;
=> 제로베이스 데이터베이스는 기본값 자료형은 다국어를 지원 및 이모지 문자(이모티콘)도 사용(utf8mb4)
show databases;
테이블이란?
데이터베이스에서 데이터를 형태를 정해 모아 놓은 저장공간
쉽게 말해 행과 열로 이루어진 표
-> 데이터베이스안에서실제데이터가저장되는형태이고, 행(Row)과열(Column)로구성된데이터모음
테이블 이름 수정 = 엑셀이름.xlsx 변경하는 것과 비슷
CREATE TABLE tablename[테이블 이름]
(
columnname[컬럼이름] datatype[데이터타입],
columnname[컬럼이름] datatype[데이터타입],
...
)
use zerobase;
테이블 생성 예제
: id(int)와 name(varchar(16)) 칼럼을가지는 mytable 이라는이름의테이블생성
CREATE TABLE mytable(id int, name varchar(16)); #varchar(16): 16byte 할당
CREATE TABLE mytable
(
id int,
name varchar(16)
);
# => 들여쓰기 정해진 것은 없으나 판다스와 비슷하게 스페이스 4번해줌
# => varchar(16): 파이썬의 str, 판다스의 object
SHOW TABLES;
DESC tablename;
mytable 테이블정보확인
DESC mytable;
예제
- name(varchar(16)), type(varchar(16)) 을가진 animal 테이블을생성하고확인하세요.
CREATE TABLE animal(name varchar(16), type varchar(16));
create table animal
( name varchar(16),
type varchar(16)
);
show tables;
desc animal;
1. Table 변경
ALTER TABLE tablename
RENAME new_tablename
mytable 이름을 person 으로변경
ALTER TABLE mytable RENAME person;
show tables;
ALTER TABLE tablename
ADD COLUMN columnname datatype;
person 테이블에 agee(double) 컬럼추가
ALTER TABLE person ADD COLUMN agee double;
=> double은 실수형
desc person;
ALTER TABLE tablename
MODIFY COLUMN columnname datatype;
person 테이블의 agee 컬럼의데이터타입을 int 로변경
ALTER TABLE person
MODIFY COLUMN agee int;
desc person;
ALTER TABLE tablename
CHANGE COLUMN old_columnname new_columnname new_datatype;
person 테이블의 agee 컬럼이름을 age 로변경
ALTER TABLE person
CHANGE COLUMN agee age int;
desc person;
=> change는 컬럼의 이름과 데이터타입 두가지를 동시에 변경할 수 있다.
ALTER TABLE tablename
DROP COLUMN columnname;
person 테이블의 age 컬럼을삭제
ALTER TABLE person
DROP COLUMN age;
desc person;
2. Table 삭제
1.Table 삭제문법
DROP TABLE tablename;
person 테이블삭제
DROP TABLE person;
show tables;
예제
- animal 테이블에 age(int) 컬럼을추가하고확인하세요.
- animal 테이블에 old(int) 컬럼을추가하고확인하세요.
- animal 테이블에서 age(int) 컬럼을삭제하고확인하세요.
- animal 테이블에서 old(int) 컬럼이름과데이터타입을 sex(char)로변경하고확인하세요. (설명: 컬럼이름과데이터타입을한번에변경할수있다.)
- animal 테이블을삭제하고확인하세요.
<문제풀이를 위한 실습환경 구축>
create database testdb;
show databases;
use testdb;
CREATE TABLE animal(name varchar(16), type varchar(16));
desc animal;
- animal 테이블에 age(int) 컬럼을추가하고확인하세요.
alter table animal add column age int;
desc animal;
- animal 테이블에 old(int) 컬럼을추가하고확인하세요.
alter table animal add column old int;
desc animal;
- animal 테이블에서 age(int) 컬럼을삭제하고확인하세요.
alter table animal drop column age;
desc animal;
- animal 테이블에서 old(int) 컬럼이름과데이터타입을 sex(char)로변경하고확인하세요. (설명: 컬럼이름과데이터타입을한번에변경할수있다.)
alter table animal change column old sex char;
desc animal;
- animal 테이블을삭제하고확인하세요.
drop table animal;
show tables;