본문 바로가기

데이터베이스

DBMS - (14) data modification statement

DBMS - (14) data modification statement

<그림 1: relation example>

Inserting new data(2 methods)
- insert into Table values(A1,A2,...,An);
- insert into Table [select-statement];

Deleting existing data
- delete from Table where condition;

Updating existing data
- update Table set A1=Expr1, A2=Expr2,..., An=Expr(n) where condition;

Insert
Q1)
insert into College values('Carnegie Mellon', 'PA', 11500);

Q2)
insert into Apply (select sID, 'Carnegie Mellon', 'CS', null from Student where sID not in (select sID from Apply));
// Apply를 하지 않은 학생들을 대상으로 Carnegie Mellon을 지원하는 튜플 추가

Q3)
insert into Apply (select sID, 'Carnegie Mellon', 'EE', 'Y' from Student where sID in (select sID from Apply where major='EE' and decision='N));
// EE 전공으로 지원해서 탈락한 학생을 Carnegie Mellon EE에 합격 추가

Delete
Q4)
delete from Student where sID in (select sID from Apply group by sID having count(distinct major) > 2);
// 2개를 초과하는 전공을 지원한 학생을 삭제
delete 쿼리를 sub-query + in keyword와 함께 유용하게 사용할 수 있음

Q5)
delete from College where cName not in (select cName from Apply where major='cs');
// 학생들이 cs전공으로 지원하지 않은 대학교 삭제

Update
Q6)
update Apply
set decision='Y', major='economics'
where cName='Carnegie Mellon'
and sID in (select sID from Student where GPA < 3.6);
// GPA가 3.6미만인 학생들 중 Carnegie Mellon에 지원한 학생은 economics 전공 합격으로 수정

Q7)
update Apply
set major='CSE'
where major='EE'
and sID in (select sID from Student
                   where GPA >= all (select GPA from Student where sID in (select sID from Apply where major = 'EE')));
// EE에 지원한 학생들 중 가장 높은 GPA를 가진 학생은 전공을 CSE로 수정

Q8)
update Student
set GPA=(select max(GPA) from Student), sizeHS=(select min(sizeHS) from Student);
// update 쿼리에 aggregation function을 사용할 수 있음  

Reference
https://www.youtube.com/watch?v=qKNb8YQYTZg&list=PL6hGtHedy2Z4EkgY76QOcueU8lAC4o6c3&index=17

'데이터베이스' 카테고리의 다른 글

DBMS - (16) relational design overview  (0) 2019.08.15
DBMS - (15) join operator  (0) 2019.08.04
DBMS - (13) null value  (0) 2019.08.04
DBMS - (12) aggregation function  (0) 2019.08.04
DBMS - (11) sub-query[from]  (0) 2019.08.04