Postgresql 专题
专题目录
您的位置:database > Postgresql专题 > PostgreSQL NULL值
PostgreSQL NULL值
作者:--    发布时间:2019-11-20

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)

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册