教程 > postgresql 教程 > 阅读:50

postgresql null 值——迹忆客-ag捕鱼王app官网

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 表示强制字段始终包含值。这意味着,如果不向字段添加值,就无法插入新记录或者更新记录。

具有 null 值的字段表示在创建记录时可以留空。

在查询数据时,null 值可能会导致一些问题,因为一个未知的值去与其他任何值比较,结果永远是未知的。

另外无法比较 null 和 0,因为它们是不等价的。

示例

创建 ,数据内容如下:

jiyik_db=# select * from 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 | south-hall|  45000
  7 | james |  24 | houston   |  10000
(7 rows)

接下来我们用 update 语句把几个可设置为空的字段设置为 null :

jiyik_db=# update company set address = null, salary = null where id in(6,7);

现在 company 表长这样:

jiyik_db=# select * from 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

现在,我们用 is not null 操作符把所有 salary(薪资) 值不为空的记录列出来:

jiyik_db=# select  id, name, age, address, salary from company where salary is not null;

结果如下:

 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

is null 用来查找为 null 值的字段。

下面是 is null 操作符的用法,列出 salary(薪资) 值为空的记录:

jiyik_db=#  select  id, name, age, address, salary from company where salary is null;

结果如下:

id | name  | age | address | salary
---- ------- ----- --------- --------
  6 | kim   |  22 |         |
  7 | james |  24 |         |
(2 rows)

查看笔记

扫码一下
查看教程更方便
网站地图