Database
[DB] ' '(empty string) 과 null 의 차이
나프초
2024. 6. 11. 22:41
데이터베이스 종류에 따라 ' '(empty string) 과 null 처리 방법이 다르다.
아래와 데이터를 입력했다고 가정해보고 결과 차이를 확인해보자.
insert into tmp_table (id, name) values (1, 'cho');
insert into tmp_table (id, name) values (2, '');
insert into tmp_table (id, name) values (3, null);
1. Oracle
Oracle 에서는 ' ' 과 null 을 동일하게 본다. 정확하게는 ' ' 이 null 로 처리된다.
-- '' 과 null 처리
select id from tmp_table where name is null; --2, 3
select id from tmp_table where name is not null; --1
select id from tmp_table where name = ''; --2,3
2. MySQL, PostgreSQL 등
MySQL, PostgreSQL 에서는 '' 과 null을 다르게 본다.
따라서 쿼리 조건문에 AA = ' ' or AA is null 로 각각 작성해주어야 한다. (full scan 위험도 증가)
-- '' 과 null 처리
select id from tmp_table where name is null; --3
select id from tmp_table where name is not null; --1, 2
select id from tmp_table where name = ''; --2
3. '' 과 null의 길이(length) 계산
null은 연산 자체가 불가능하다. 길이 계산도 연산이기 때문에 결과가 null이니 쿼리 작성시 주의해야 한다.
--길이
select length(name) from tmp_table where name is null; --null
select length(name) from tmp_table where name = ''; --0