728x90
※MySql과 차이점 테이블 생성 시
제약조건 선언(constraint) + 제약조건명 + 제약조건 이 들어감,
※오라클에서는 not null을 제외한 제약 조건은 테이블 레벨 문법, 컬럼 레벨 문법을 사용할 수 있음
서브쿼리 구문을 사용한 테이블 생성
-- 복사본 테이블 생성
create table dept80
as
select employee_id, last_name, salary*12 ANNSAL, hire_date
from employees
where department_id = 80;
--설명
-- 1
select employee_id, last_name, salary*12 ANNSAL, hire_date
from employees
where department_id = 80;
-- 2
create table dept80
-- 구조 및 조회
desc dept80;
select * from dept80;
※
-- 구조는 같지만 데이터는 비어있는 복사본의 테이블 생성
create table copy_emp
as select * from employees where 1 = 2;
-- 기존 테이블의 데이터를 복사본의 테이블에 삽입(복사)
insert into copy_emp
select * from employees;
-- == 테이블과 구조, 데이터가 동일한 테이블 생성(백업용 ,테스트용)
create table copy_emp
as select* from employees;
테이블 수정(alter table)
- 컬럼 추가 : add
alter table dept80
add(job_id varchar2(20));
desc dept80;
새롭게 추가된 컬럼은 항상 마지막 컬럼으로 추가되며 null값이 들어감
- 컬럼 수정(데이터 타입, 컬럼 사이즈, default값) : modify
alter table dept80
modify (last_name varchar2(30));
desc dept80
컬럼 사이즈를 늘리는 것은 가능하지만, 줄이는 것은 기본적으로 들어가 있는 데이터 크기보다 작게된다면 안될 수 있음
- 컬럼 삭제 : drop
컬럼 및 컬럼 데이터 삭제
alter table dept80
drop (job_id);
-- 또는
alter table dept80
drop column job_id;
- 제약 조건 추가 : add
※복사본을 만들 시 not null 제약조건만 추가됨
create table emp2
as select * from employees;
employee_id PK, email UK, salary CK, manager_id FK(employee_id), department_id FK(departments(department_id)) 추가하기
-- 컬럼 레벨 문법 : nn을 포함한 모든 제약 조건(nn, pk, fk, ck, uk)
alter table 테이블명
modify 컬럼명 constraint 제약조건명 제약조건유형;
-- =>
alter table emp2
modify employee_id constraint e2_eid_pk primary key;
alter table emp2
modify email constraint e2_email_uk unique;
alter table emp2
modify salary constraint e2_sal_ck check(salary>0);
alter table emp2
modify manager_id constraint e2_mid_fk references employees(employee_id);
alter table emp2
modify department_id constraint e2_did_fk references departments(department_id);
-- ==
-- 테이블 레벨 문법 : nn을 제외한 모든 제약 조건(pk, fk, ck, uk)
alter table 테이블명
add constraint 제약조건명 제약조건유형(컬럼명);
-- =>
alter table emp2
add constraint e2_eid_pk primary key(employee_id);
alter table emp2
add constraint e2_email_uk unique(email);
alter table emp3
add constraint e2_sal_ck check(salary>0);
alter table emp2
add constraints e2_mid_fk foreign key(manager_id) references employees(employee_id);
alter table emp2
add constraints e2_did_fk foreign key(department_id) references departments(departement_id);
※ foreign key 제약 조건의 경우 컬럼 레벨 문법과 테이블 레벨 문법 차이가 존재함
references 테이블명(컬럼명) / foreign key(컬럼명) references 테이블명(컬럼명)
- 제약 조건 삭제
- 컬럼명 수정
- 제약조건명 수정
- 테이블명 수정
728x90
'KDT > DB' 카테고리의 다른 글
240306 DB - 데이터정의어(DDL) - View, Sequence 1 (0) | 2024.03.06 |
---|---|
240304 DB - SQL활용 데이터정의어(DDL) - table3 (0) | 2024.03.04 |
240222 DB - SQL활용 데이터정의어(DDL) - table 1 (0) | 2024.02.22 |
240221 DB - Data Dictionary, SQL 활용 (0) | 2024.02.21 |
240216 DB - 치환 변수 (0) | 2024.02.16 |