14. SQL NULL값 처리 (IS NOT NULL, IS NULL)

김요한·2024년 6월 26일
  • 전에 배운 내용대로만 하였을 때 사용 할 수 없는 값일 경우에는 아래와 같이 0으로 처리해 줄 수 있다.


위와 같이 rating에 사용할 수 없는 값 Not given이 있다.

select restaurant_name,
       avg(rating) average_of_rating,
       avg(if(rating<>'Not given', rating, null)) average_of_rating2
from food_orders
group by 1
# 사용할 수 없는 값 Not given을 null값 즉 0으로 간주하는 값으로 제외해줬다.

IS NOT NULL

기본구조

- where (지정컬럼) IS NOT NULL

하지만 더욱 명확하게 NULL값을 처리해주기 위해 NULL문법을 사용한다.

select a.order_id,
       a.customer_id,
       a.restaurant_name,
       a.price,
       b.name,
       b.age,
       b.gender
from food_orders a left join customers b on a.customer_id=b.customer_id
where b.customer_id is not null 
          #where 조건절에 is not null (null값을 제외하고 조회할 수 있도록 했다)

IS NULL, COALESCE

기본구조

IS NULL = WHERE (지정컬럼) IS NULL

NULL값을 대체해주는 함수

  • coalesce = coalesce( 지정컬럼 , 대체값 )


  • 조건에 null 값을 지정해주고 대체 해주는 방법도 있다.
select a.order_id,
       a.customer_id,
       a.restaurant_name,
       a.price,
       b.name,
       b.age,
       coalesce(b.age, 20) "null 제거",
       b.gender
from food_orders a left join customers b on a.customer_id=b.customer_id
where b.age is null

#null 값인 age를 coalesce로 제거해서 20으로 대체한다.

0개의 댓글