본문 바로가기
데이터베이스설계

[데이터베이스설계] 3-15 DB 변경연산 - update

by 젼젼39 2025. 2. 15.
update update 테이블명 set 변경식         (수정할 컬럼명 (비교연산자) 계산부분)
                                   (수정할 컬럼명 (비교연산자) SFW 서브쿼리)

Q) give a 5% salary raise to all instructors
=> update instructor
     set salary = salary * 1.05
 

Q) give a 5% salary raise to those instructors who earn less than 70000
=> update instructor
    set salary = salary * 1.05
    where salary < 70000 ;           //where 뒤에 조건문
 

Q) give a 5% salary raise to instructors whose salary is less than average
=> update instructor
     set salary = salary * 1.05
     where salary < (select avg(salary)
.                              from instructor ) ;        //서브쿼리 먼저 실행됨


Q) increase salaries of instructors whose salary is over $100,000 by 3%, and all others by a 5%
=> update instructor
    set salary = salary * 1.03
    where salary > 100000 ;
    update instructor
    set salary = salary * 1.05
    where salary <= 100000;              //만약 이 순서를 바꾸면 계산 꼬인다. 아님 case쓰기
 
  2가지 케이스에 대해 고려해야 해서, update문이 2번이다
 

Q) same query as before but with case statement
=> update instructor
     set salary = ( case
                                when salary <= 100000 then salary * 1.05
                                else salary * 1.03
                            end )
    2번의 update가 아니라 1번의 update.
    //set salary = ( case
    //set salary = T.salary * ( case ~~~ 도 가능)
 

// mark(ID, score) 릴레이션
select ID, case
                      when score < 40 then ‘F’
                      when score < 60 then ‘C’
                      when score < 80 then ‘B’
                      else ‘A’
                 end
from marks
 
//위의 표를 with grade as ( ) 안에 넣으면,
아래 SFW문에서 grade에 대해 group by grade한 뒤 count(ID)하면 점수당 학생수가 됨