postgresql null
是用于表示缺少值的术语。 表中的null
值是一个字段中的值,显示为空白。
具有null
值的字段是没有值的字段。要知道一个null
值与零值或包含空格的字段不同是非常重要的。
语法:
创建表时使用null
的基本语法如下:
create table company(
id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real
);
这里,not null
表示该列应该始终接受给定数据类型的显式值。有两列不使用not null
。 因此这意味着这些列可以为null
。
具有null
值的字段是在创建记录期间留空的字段。
然而,当选择数据时,null
值可能会导致问题,因为当将未知值与任何其他值进行比较时,结果始终是未知的,不包括在最终结果中。 考虑下表-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
,如下所示:
h3_db=# update company set address = null, salary = null where id in(6,7);
现在,查询company
表应该有以下记录:
id | name | age | address | salary
----+-------+-----+-------------+--------
1 | paul | 32 | california | 20000
2 | allen | 25 | texas | 15000
3 | teddy | 23 | norway | 20000
4 | mark | 25 | rich-mond | 65000
5 | david | 27 | texas | 85000
6 | kim | 22 | |
7 | james | 24 | |
(7 rows)
接下来,使用is not null
运算符列出salary
不为null
的所有记录:
h3_db=# select id, name, age, address, salary
from company
where salary is not null;
postgresql上面的语句将产生以下结果:
id | name | age | address | salary
----+-------+-----+------------+--------
1 | paul | 32 | california | 20000
2 | allen | 25 | texas | 15000
3 | teddy | 23 | norway | 20000
4 | mark | 25 | rich-mond | 65000
5 | david | 27 | texas | 85000
(5 rows)
以下是使用is null
运算符,查询列出salary
列的值为null
的所有记录:
h3_db=# select id, name, age, address, salary
from company
where salary is null;
postgresql上面的语句将产生以下结果:
id | name | age | address | salary
----+-------+-----+---------+--------
6 | kim | 22 | |
7 | james | 24 | |
(2 rows)