본문 바로가기
백엔드/SQL

DML: INSERT & DELETE & UPDATE

by dustnn 2025. 4. 11.
SELECT를 제외한 DML 구문: INSERT & DELETE & UPDATE

 

DELETE: 테이블의 투플 삭제
delete from instructor where dept_name = 'Finance';

 

 

INSERT: 테이블에 투플 삽입

 

다음과 같이 테이블을 생성했다고 할 때,

create table person (
	id char(10),
    name char(40),
    father char(10),
    mother char(10),
    primary key(id),
    foreign key(father) references person(id),
    foreign key(mother) references person(id)
);
insert into person (id, name, father, mother) values('0000', 'papa', null, null); //속성 삽입하고 값 대입
insert into person values ('1111' 'mama', null, null); //속성 앞에서 만들어주었으므로 대입만 해주면 됨
insert into person values ('2222', 'first', '0000', '1111');

 

‼️ 참조관계 주의 ‼️

참조되는 부모 테이블의 데이터가 존재할 때 자식 테이블의 데이터 삽입 가능

 

<가능>

insert into person (id, name, father, mother) values ('3333', 'someone', null, null); //테이블에 엄마 아빠 정보 없음
insert into person (id, name, father, mother) values ('4444', 'grand', '2222', '3333'); //'2222'와 '3333' 투플 존재해야만 가능

 

<에러>

insert into person (id, name, father, mother) values ('4444', 'grand', '2222' , '3333'); //아직 '3333' 투플은 없기 때문에 에러
insert into person (id, name, father, mother) values ('3333', 'someone', null, null); //얘를 먼저 써줘야 함

 

<가능>-위 에러 해결

insert into person (id, name, father, mother) values ('4444', 'grand', '2222', null); //참조하고 싶은 부모테이블이 없다면 null로 일단 세팅해두고 update
insert into person (id, name, father, mother) values ('3333', 'someone', null, null); 
update person set mother = '3333' where id = '4444'; //id='4444'인 투플 중에서 mother 컬럼을 '3333'으로 갱신해달라

 

UPDATE: 테이블의 투플 변경

 

<교수들의 급여를 전체적으로 5% 인상>

update instructor set salary = salary * 1.05;

 

=> instructor 테이블에서 salary 컬럼 값들을 'salary*1.05' 값으로 갱신시켜라

 

 

<급여가 70000 미만인 교수들의 급여를 5% 인상>

update instructor set salary = salary * 1.05 where salary < 70000;

 

=> (조건 부여) instructor 테이블에서 'salary<70000'인 투플들의 salary 컬럼 값들을 'salary*1.05' 값으로 갱신시켜라

 

‼️UPDATE 실행 순서가 중요한 경우‼️

<급여가 90000 초과인 교수는 급여를 3% 인상하고

급여가 90000 이하인 교수는 급여를 5% 인상하는 경우>

 

(point1) update가 두 번 이루어져야 함

- update1: 급여가 90000 초과인 교수는 급여를 3% 인상

- update2: 급여가 90000 이하인 교수는 급여를 5% 인상

(point2) "update1->update2" 순서로 이루어져야 함

update2->update1 순서라면 update2에 의해 salary>90000이 된 교수가 update1에 의해 한 번 더 인상받게 됨

 

=> 의미상 알맞게 순서 정할 것