SQL/DDL
[DDL] CREATE
dark pepper
2023. 4. 12. 15:46
DDL은 스키마, 도메인, 테이블, 뷰 인덱스를 정의하거나 변경 또는 삭제할 때 사용하는 언어이다.
CREATE
스키마, 도메인, 테이블, 뷰, 인덱스를 정의한다.
표기형식
CREATE TABLE 테이블명
(속성명 데이터_타입 [DEFAULT 기본값] [NOT NULL], ...
[, PRIMARY KEY(기본키_속성명, ...)]
[, UNIQUE KEY(대체키_속성명, ...)]
[, FOREIGN KEY(외래키_속성명, ...)]
[REFERENCES 참조 테이블(기본키_속성명, ...)]
[ON DELETE 옵션]
[ON UPDATE 옵션]
[, CONSTRAINT 제약조건명][CHECK (조건식)]);
예제
예제1
테이블 생성
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
예제2
Constraint로 단일 컬럼을 PK 지정
CREATE TABLE table_name (
column1 datatype not null,
column2 datatype,
column3 datatype,
PRIMARY KEY (column1)
);
예제3
Constraint로 컬럼의 조합을 PK 지정
CREATE TABLE table_name (
column1 datatype not null,
column2 datatype not null,
column3 datatype,
Constraint PK_table PRIMARY KEY (column1, column2)
);
예제 4
Constraint로 FK 지정
CREATE TABLE other_table (
other_id datatype not null primary key,
)
CREATE TABLE table_name (
column1 datatype not null,
column2 datatype not null,
this_column datatype,
Foreign Key (this_column) references other_table(other_id)
);
예제 5
FK 예제
CREATE TABLE `review` (
`id` int NOT NULL,
`content` varchar(2048) DEFAULT NULL,
`user_id` int DEFAULT NULL,
`product_id` int unsigned NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
)