hive中空值判斷基本分兩種
一、NULL 與 \N
hive在底層數據中如何保存和標識NULL,是由 alter table name SET SERDEPROPERTIES('serialization.null.format' = '\N'); 參數控制的
比如:
1、設置 alter table name SET SERDEPROPERTIES('serialization.null.format' = '\N');
則:底層數據保存的是'\N',通過查詢顯示的是'NULL'
這時如果查詢為空值的字段可通過 語句:a is null 或者 a='\N'
2、測試
hive> create table test(id int,name string);
hive> insert into table test(1, 'yjt');
hive> alter table test set serdeproperties("serialization.null.format"='\N');
hive> insert into table test values(2, 'yjl');
hive> insert into table test values(3, NULL);
hive> select * from test;
OK
test.id test.name
1 yjt
2 yjl
3 NULL
hive> select * from test where name is NULL;
OK
test.id test.name
3 NULL
hive> select * from test where name = '\\N'; #修改存儲空值時為'\N',但是在查詢的時候,不能使用'\\N'的方式判斷
OK
test.id test.name
Time taken: 0.182 seconds
2.設置 alter tablename SET SERDEPROPERTIES('serialization.null.format' = 'NULL');
則:底層數據保存的是'NULL',通過查詢顯示的是'NULL'
這時如果查詢為空值的字段可通過 語句:a is null 或者 a='NULL'
hive> alter table test set serdeproperties("serialization.null.format"='NULL');
hive> select * from test ;
OK
test.id test.name
1 yjt
2 yjl
3 N #以前存儲的NULL值變成了 'N'
查詢
hive> select * from test where name = 'N';
OK
test.id test.name
3 N
重新插入空值測試
hive> insert into table test values(6, NULL);
hive> select * from test;
OK
test.id test.name
1 yjt
2 yjl
3 N
4 \N
5
6 NULL
Time taken: 1.182 seconds, Fetched: 6 row(s)
hive> select * from test where name is null; #通過is null 的方式可以查到
OK
test.id test.name
6 NULL
Time taken: 0.146 seconds, Fetched: 1 row(s)
hive> select * from test where name = 'null';
OK
test.id test.name
Time taken: 0.151 seconds
hive> select * from test where name = 'NULL'; #這種方式不能查詢到存儲的空值
OK
test.id test.name
Time taken: 0.171 seconds
hive>
總結 最好還是使用is null判斷
二、'' 與 length(xx)=0
'' 表示的是字段不為null且為空字符串,此時用 a is null 是無法查詢這種值的,必須通過 a='' 或者 length(a)=0 查詢
hive>
>
> select * from test where length(name) = 0;
OK
test.id test.name
5
Time taken: 0.199 seconds, Fetched: 1 row(s)
hive> select * from test where name = '';
OK
test.id test.name
5
Time taken: 0.182 seconds, Fetched: 1 row(s)
總結,如果是空字符串,可以使用=或者length方式判斷