테이블 복사
- 제약조건은 복사되지 않는다. (not null 제외)
- 조작된 컬럼이 사용되는 경우, 반드시 컬럼명을 부여해야 한다.
- 형식
create table table_name(컬럼명, ...) as select ~~
create table test2 (직책, 성별, 급여합계)
as
select sajob, sasex, sum(sapay) from sawon
group by sajob, sasex;
직책 성별 급여합계
과장 남자 12003
부장 여자 3000
과장 여자 3900
대리 여자 4206
사원 여자 7700
대리 남자 1800
부장 남자 5803
사원 남자 4906
회장 남자 5000
create table dept_ex
as
select * from dept where 1=2;
SQL> desc dept_ex
이름 널? 유형
DEPTNO NUMBER(3)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
SQL> select * from dept_ex;
선택된 레코드가 없습니다.
DML
- 데이터 조작 명령
- 데이터 변경 명령
- 데이터 흐름 명령
- 이벤트(처리) 명령
- 트랜잭션(처리) 명령
- 실행단위 : 행
- insert, delete, update [select]
insert
insert into table_name values(값, ...);
insert into table_name(컬럼명, ...) values(값, ...)
insert into table_name[(컬럼명, ...)] select ~ ;
insert into dept_ex select * from dept;
delete
delete [from] table_name where ~ ;
truncate table dept_ex;
update
update table_name set 컬럼명 = 값, ... where ~ ;
예제
- 모든 문제는 sawon_ex, dept_ex, gogek_ex 사본 테이블을 생성하여 작업할 것
- 고객의 담당자가 없는 고객은 13번 사원으로 변경
update gogek_ex set godam = 13 where godam is null;
- 13번 담당자를 갖는 고객의 담당자를 null로 변경
update gogek_ex set godam = [null||''] where godam = 13;
- sawon_ex테이블에 직책이 사원인 사원들의 sawon 테이블 모든 컬럼 정보를 입력
insert into sawon_ex select * from sawon where sajob = '사원';
- 17번 사원의 부서와 같은 사원들의 직책을 17번 사원의 직책으로 변경
update sawon_ex
set sajob = (select sajob from sawon where sabun = 17)
where deptno = (select deptno from sawon where sabun = 17);
update sawon_ex
set sapay = sapay * 1.1
where deptno = (select deptno from dept_ex where dname = '영업부');
- 관리부서 사원 중 회사의 평균급여보다 낮은 사원들을 삭제
delete from sawon_ex
where deptno = (select deptno from dept_ex where dname = '관리부')
and sapay < (select avg(sapay) from sawon_ex);
- 총무부 사원들의 급여를 자신이 속한 직책의 평균 급여로 변경
update sawon_ex s
set sapay = (select avg(sapay) from sawon_ex t where t.sajob = s.sajob)
where deptno = (select deptno from dept_ex where dname = '총무부');
병합
- 한 번의 조건으로 입력 또는 변경을 수행하는 구문
- 형식
merge into 테이블명 using 비교테이블명 on(두 테이블의 비교문 - 기본키대상)
when matched then
update set ~
when not matched then
insert values~;
- sawon테이블과 비교하여 사원정보가 sawon_10테이블에 존재하면 급여를 10% 인상하고, sawon_10 테이블에 존재하지 않는다면 입력
create table sawon_10 as select * from sawon where deptno = 10;
merge into sawon_10 s10
using sawon s
on (s10.sabun = s.sabun)
when matched then de
update set sapay = sapay * 1.1
when not matched then
insert values (s.sabun, s.saname, s.deptno, s.sajob, s.sapay, s.sahire, s.sasex, s.samgr);