[Oracle] SQL Class 9 - DML 명령, 실습예제, 병합(merge)
2023.11.6
DML 란?
- 데이터 조작명령, 데이터 변경명령, 트렌젝션(처리) 명령, 데이터 흐름명령, 이벤트 명령
- 실행대상: 행**** 단위
-- insert(입력), update(변경), delete(삭제)
1. insert (입력)
1) insert into table_name values(값, ... ); // 전체 컬럼값을 가진 입력
2) insert into table_name(컬럼명, ... ) values(값, ... ) // 선택 컬럼값을 가진 입력 **가장 많이 씀
3) insert into table_name( [컬럼명]) select ~; // 다중행 단위의 입력
2. delete(삭제)
SQL > delete [from] table_name where~ // where절 참일때 출력, 해당 행(row) 삭제할때 사용.
단, 테이블내의 모든 행을 삭제하는 경우를 사용해야 됨.
3. update
- update table_name set 컬럼=값, ... where~
실습예제
* 모든 문제는 sawon_exx, dept_exx, gogek_exx 사본 테이블을 생성하여 작업할 것
SQL> create table sawon_exx as select *from sawon;
SQL> create table dept_exx as select *from dept;
SQL> create table gogek_exx as select *from gogek;
1) 고객의 담당자가 없는 고객은 13번 사원으로 변경
SQL> update gogek_exx set godam=13
where godam is null;
2) 13번 담당자를 갖는 고객의 담당자를 null로 변경
SQL> update gogek_exx set godam=null
where godam=13;
3) sawon_ex 테이블에 직책이 사원인 사람들의 sawon 테이블 모든 컬럼정보를 입력
SQL> insert into table sawon_exx select *from sawon
where sajob='사원';
혹은 insert into table sawon_exx(sabun, saname,sapay)
select sabun, saname, sapay from sawon where sajob='사원';
// sabun, saname, sapay를 쓰면, select에도 동일하게 입력해야 됨.
4) 17번 사원의 부서와 같은 사원들의 직책을 17번 사원의 직책으로 변경
SQL> update sawon_exx
set sajob=(select sajob from sawon where sabun=17)
where deptno=(select deptno from sawon where sabun=17);
// set절에는 사원의 직책, where절에는 17번 사원의 직책
5) 영업부 사원들의 급여를 10% 인상 변경 --> 테이블 2개로 값 변경
SQL> update sawon_exx
set sapay=sapay*1.1
where deptno=(select deptno from dept_exx where dname='영업부');
6) 관리부서 사원 중에서 회사의 평균급여보다 낮은 사람들을 삭제
SQL> delete from sawon_exx
where deptno=(select deptno from dept_exx where dname='관리부')
and sapay>(select avg(sapay) from sawon_exx);
7) 총무부 사원들의 급여를 자신이 속한 직책의 평균급여로 변경 --> 상관쿼리
SQL> update sawon_exx s
set sapay=(select avg(sapay) from sawon_exx e where e.sajob=s.sajob)
where deptno=(select deptno from dept_exx where dname='총무부');
## Merge(병합)
-- 한 번의 조건으로 입력 or 변경을 수행하는 문구
-- 형식
merge into 테이블명 using 비교 테이블명 on(두 테이블 비교문-기본키 대상)
when matched then
update set~
when not matched then
insert values ~ ;
(연습1)
sawon 테이블과 비교하여 사원정보가
sawon_10 테이블에 존재하면 급여를 10% 인상하고, sawon_10 테이블에 존재하지 않는다면 입력하라.
SQL> create table sawon_10 // sawon_10 테이블 생성.
SQL> select *from sawon
merge into sawon_10 s10
using sawon s on(s.sawon=s10.sabun)
when matched then
update set sapay=sapay*1.1
when not matched then
insert values (s.sabun, s.saname, s.deptno, s.sapay, s.sahire, s.sasex, s.samgr);