내일배움 사전캠프

[내일배움 사전캠프 5일차]SQL로 조건문 작성하기

hyeon-ji 2026. 5. 4. 17:09

SQL 3주차 강의를 학습하며 조건문 if, case를 활용하여 내가 원하는 값을 설정하는 법을 배웠다. 추가로 다양한 함수를 이용하여 실무에서 실용적으로 활용할 수 있는 방법들도 함께 학습했다.


■ Formatting

 

▶컬럼 명 바꾸기

 

● replace문

함수 의미
replace 지정값으로 컬럼명 바꾸기
substr 특정문자만 뽑아내기
concat 원하는 데이터들을 모아 작성
replace(바꿀 컬럼, 현재 값, 바꿀 값)
select restaurant_name "원래 상점명",
       replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명"
from food_orders
where restaurant_name like '%Blue Ribbon%'

 

● substr 문

substr(조회할 컬럼, 시작 위치, 글자 수)
// '글자 수'를 특정하지 않고 싶은 경우에는 생략 가능
select addr "원래 주소",
       substr(addr, 1, 2) "시도"
from food_orders
where addr like '%서울특별시%'

 

● concat 문

concat(붙이고 싶은 값1, 붙이고 싶은 값2, 붙이고 싶은 값3, ...)

[실습1] 이메일 도메인 별 고객 수와 평균 연령 구하기

select substr(email, 10) "도메인",
count(1) "고객 수",
avg(age) "편균 연령"
from customers
group by 1

//group by 1 또는 group by substr(email, 10) --> 둘 다 가능

 

[실습2] [지역(시도)]음식점 이름 (음식종류) 컬럼 만들고, 총 주문건수 구하기

select concat('[', substr(addr, 1, 2), ']', restaurant_name, ' (', cuisine_type, ')') "음식점",
count(1) "주문 건수" 
from food_orders
group by 1


▶ 조건 추가하기

 

● If문

ex) 음식 타입을 'Korean'일 때는 '한식', 아닌 경우에는 '기타'로 지정하고 싶은 경우 사용

      주소의 시도를 '경기도'일 때는 '경기도' 아닐 때는 앞의 두 글자만 사용하고 싶은 경우 사용

if(조건, 조건 충족할 때, 조건 충족하지 못할 때)
select addr "원래 주소",
       if(addr like '%평택군%', replace(addr, '문곡리', '문가리'), addr) "바뀐 주소"
from food_orders
where addr like '%문곡리%'

 

● case문

조건 지정 시 두 개 이상 지정해야 하는 경우 사용한다.

case 활용하여 여러번의 if문 적용 효과낼 수 있다.

case when 조건1 then 값(수식)1
     when 조건2 then 값(수식)2
     else 값(수식)3
     end
//else는 조건이 부합하지 않을 경우 사용, 조건이 부합하지 않은 경우가 없다면 생략 가능
select case when cuisine_type='Korean' then '한식'
when cuisine_type in ('Japanese', 'Chinese') then '아시아'
else '기타' end "음식 타입",
cuisine_type
from food_orders


▷ User Segmentation

select case when (age between 10 and 19) and gender='male' then '10대 남성'
            when (age between 10 and 19) and gender='female' then '10대 여성'
            when (age between 20 and 29) and gender='male' then '20대 남성'
            when (age between 20 and 29) and gender='female' then '10대 여성' end "고객 분류",
       name, 
       age,
       gender
            from customers
where age between 10 and 29

 

조건에 따른 다른 연산식 적용하기 1

select case when delivery_time>30 then price*0.1*if(addr like '%서울%', 1.1, 1)
            when delivery_time>25 then price*0.05*if(addr like '%서울%', 1.1, 1)
            else 0 end "수수료",
       restaurant_name,
       order_id,
       price,
       delivery_time,
       addr
from food_orders

 

 조건에 따른 다른 연산식 적용하기 2

select case when day_of_the_week='weekday' then 3000*if(quantity>3, 1.2, 1)
            when day_of_the_week='weekend' then 3500*if(quantity>3, 1.2, 1)
            else 0 end "배달 할증료",
       restaurant_name,
       order_id,
       day_of_the_week,
       quantity
from food_orders


[과제] 배달이 늦었는지 판단하는 값 만들기

select order_id,
       restaurant_name,
       day_of_the_week,
       delivery_time,
       case when day_of_the_week='weekday' then if(delivery_time<25, 'On-time', 'Late')
            when day_of_the_week='weekend' then if(delivery_time<30, 'On-time', 'Late') end "지연여부"
from food_orders

select order_id,  
       restaurant_name,
       day_of_the_week,
       delivery_time,
       case when day_of_the_week='Weekday' and delivery_time>=25 then 'Late'
            when day_of_the_week='Weekend' and delivery_time>=30 then 'Late'
            else 'On-time' end "지연여부"
from food_orders

정답은 위와 같았다. 나는 if 문을 활용하여 배달 시간이 지연되었을 경우와 아닌 경우를 지정하였는데, 정답 쿼리를 확인하니 별도의 if문 사용없이 case문 만으로도 조건을 지정해주었다.

도출된 결과를 확인하니 답을 동일함을 확인할 수 있었다. 과제를 풀어나갈 때는 case문 만으로 해결하는 법이 떠오르지 않아 if문을 활용하였는데, 정답을 확인하고 나서 case문 만을 활용하여 답변을 도출해내는 또다른 방법이 존재했음을 알게되었다. 

하나의 문제에는 하나의 답만이 존재할 것이라 생각했는데, 이번 과제를 통해 하나의 문제에 하나 이상의 답이 존재할 수 있음을 알게되었다.