共計 2572 個字符,預計需要花費 7 分鐘才能閱讀完成。
本篇文章為大家展示了 Oracle 中 Null 與空字符串的區別是什么,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
含義解釋:
問:什么是 NULL?
答:在我們不知道具體有什么數據的時候,也即未知,可以用 NULL,我們稱它為空,ORACLE 中,含有空值的表列長度為零。
ORACLE 允許任何一種數據類型的字段為空,除了以下兩種情況:
1、主鍵字段(primary key),
2、定義時已經加了 NOT NULL 限制條件的字段
說明:
1、等價于沒有任何值、是未知數。
2、NULL 與 0、空字符串、空格都不同。
3、對空值做加、減、乘、除等運算操作,結果仍為空。
4、NULL 的處理使用 NVL 函數。
5、比較時使用關鍵字用“is null”和“is not null”。
6、空值不能被索引,所以查詢時有些符合條件的數據可能查不出來,count(*) 中,用 nvl(列名,0) 處理后再查。
7、排序時比其他數據都大(索引默認是降序排列,小→大),所以 NULL 值總是排在最后。
使用方法:
SQL select 1 from dual where null=null;
沒有查到記錄
SQL select 1 from dual where null=
沒有查到記錄
SQL select 1 from dual where =
沒有查到記錄
SQL select 1 from dual where null is null;
1
———
1
SQL select 1 from dual where nvl(null,0)=nvl(null,0);
1
———
1
對空值做加、減、乘、除等運算操作,結果仍為空。
SQL select 1+null from dual;
SQL select 1-null from dual;
SQL select 1*null from dual;
SQL select 1/null from dual;
查詢到一個記錄.
注:這個記錄就是 SQL 語句中的那個 null
設置某些列為空值
update table1 set 列 1 =NULL where 列 1 is not null;
現有一個商品銷售表 sale,表結構為:
month char(6) – 月份
sell number(10,2) – 月銷售金額
create table sale (month char(6),sell number);
insert into sale values(200001 ,1000);
insert into sale values(200002 ,1100);
insert into sale values(200003 ,1200);
insert into sale values(200004 ,1300);
insert into sale values(200005 ,1400);
insert into sale values(200006 ,1500);
insert into sale values(200007 ,1600);
insert into sale values(200101 ,1100);
insert into sale values(200202 ,1200);
insert into sale values(200301 ,1300);
insert into sale values(200008 ,1000);
insert into sale(month) values(200009(注意:這條記錄的 sell 值為空)
commit;
共輸入 12 條記錄
SQL select * from sale where sell like %
MONTH SELL
—— ———
200001 1000
200002 1100
200003 1200
200004 1300
200005 1400
200006 1500
200007 1600
200101 1100
200202 1200
200301 1300
200008 1000
查詢到 11 記錄.
結果說明:
查詢結果說明此 SQL 語句查詢不出列值為 NULL 的字段
此時需對字段為 NULL 的情況另外處理。
SQL select * from sale where sell like % or sell is null;
SQL select * from sale where nvl(sell,0) like %
MONTH SELL
—— ———
200001 1000
200002 1100
200003 1200
200004 1300
200005 1400
200006 1500
200007 1600
200101 1100
200202 1200
200301 1300
200008 1000
200009
查詢到 12 記錄.
Oracle 的空值就是這么的用法,我們最好熟悉它的約定,以防查出的結果不正確。
但對于 char 和 varchar2 類型的數據庫字段中的 null 和空字符串是否有區別呢?
作一個測試:
create table test (a char(5),b char(5));
SQL insert into test(a,b) values(1 , 1
SQL insert into test(a,b) values(2 , 2
SQL insert into test(a,b) values(3 , – 按照上面的解釋,b 字段有值的
SQL insert into test(a) values(4
SQL select * from test;
A B
———- ———-
1 1
2 2
3
4
SQL select * from test where b= —- 按照上面的解釋,應該有一條記錄,但實際上沒有記錄
未選定行
SQL select * from test where b is null;—- 按照上面的解釋,應該有一跳記錄,但實際上有兩條記錄。
A B
———- ———-
3
4
SQL update table test set b= where a= 2
SQL select * from test where b=
未選定行
SQL select * from test where b is null;
A B
———- ———-
2
3
4
上述內容就是 Oracle 中 Null 與空字符串的區別是什么,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注丸趣 TV 行業資訊頻道。