SQLite NULL 值
sqlite null 值
sqlite 的 null 是用來表示一個缺失值的項。表中的一個 null 值是在字段中顯示為空白的一個值。
帶有 null 值的字段是一個不帶有值的字段。null 值與零值或包含空格的字段是不同的,理解這點是非常重要的。
1. 語法
創(chuàng)建表時使用 null 的基本語法如下:
sqlite> create table company( id int primary key not null, name text not null, age int not null, address char(50), salary real );
在這里,not null 表示列總是接受給定數(shù)據(jù)類型的顯式值。這里有兩個列我們沒有使用 not null,這意味著這兩個列可以為 null。>
帶有 null 值的字段在記錄創(chuàng)建的時候可以保留為空。
null 值在選擇數(shù)據(jù)時會引起問題,因為當把一個未知的值與另一個值進行比較時,結(jié)果總是未知的,且不會包含在最后的結(jié)果中。假設有下面的表,company 的記錄如下所示:
id name age address salary ---------- ---------- ---------- ---------- ---------- 1 paul 32 california 20000.0 2 allen 25 texas 15000.0 3 teddy 23 norway 20000.0 4 mark 25 rich-mond 65000.0 5 david 27 texas 85000.0 6 kim 22 south-hall 45000.0 7 james 24 houston 10000.0
讓我們使用 update 語句來設置一些允許空值的值為 null,如下所示:
sqlite> update company set address = null, salary = null where id in(6,7);
現(xiàn)在,company 表的記錄如下所示:
id name age address salary ---------- ---------- ---------- ---------- ---------- 1 paul 32 california 20000.0 2 allen 25 texas 15000.0 3 teddy 23 norway 20000.0 4 mark 25 rich-mond 65000.0 5 david 27 texas 85000.0 6 kim 22 7 james 24
接下來,讓我們看看 is not null 運算符的用法,它用來列出所有 salary 不為 null 的記錄:
sqlite> select id, name, age, address, salary from company where salary is not null;
上面的 sqlite 語句將產(chǎn)生下面的結(jié)果:
id name age address salary ---------- ---------- ---------- ---------- ---------- 1 paul 32 california 20000.0 2 allen 25 texas 15000.0 3 teddy 23 norway 20000.0 4 mark 25 rich-mond 65000.0 5 david 27 texas 85000.0
下面是 is null 運算符的用法,將列出所有 salary 為 null 的記錄:
sqlite> select id, name, age, address, salary from company where salary is null;
上面的 sqlite 語句將產(chǎn)生下面的結(jié)果:
id name age address salary ---------- ---------- ---------- ---------- ---------- 6 kim 22 7 james 24