在本教程中,我们将介绍null概念,并演示如何使用sql is null
和is not null
运算符来测试表达式是否为null
。
null
在sql中很特殊。 null
表示数据未知的值,可以简单理解为表示:不适用 或不存在的值。 换句话说,null
表示数据库中缺少数据。
例如,如果员工没有任何电话号码,可以将其存储为空字符串。 但是,如果在插入员工记录时不知道他的电话号码,我们将使用未知电话号码的null
值。
null
值是特殊的,因为任何与null
值的比较都不会导致true
或false
,但在第三个逻辑结果中:未知。
以下语句返回null
值。
select null = 5;
null
值甚至不等于自身,如以下语句所示。
select null = null;
在此示例中,结果为null
值。
不能使用比较运算符的等于(=
)将值与null
值进行比较。 例如,以下语句将不会产生正确的结果。
select
employee_id, first_name, last_name, phone_number
from
employees
where
phone_number = null;
要确定表达式或列的值是否为null
,请使用is null
运算符,如下所示:
expression is null;
如果表达式的结果为null
,则is null
运算符返回true
; 否则它返回false
。要检查表达式或列是否不为null
,请使用is not
运算符:
expression is not null;
如果表达式的值为null
,则is not null
返回false
; 否则它返回true
;
在这些示例中,我们将使用示例数据库中的employees
表进行演示。
mysql> desc employees;
+---------------+--------------+------+-----+---------+----------------+
| field | type | null | key | default | extra |
+---------------+--------------+------+-----+---------+----------------+
| employee_id | int(11) | no | pri | null | auto_increment |
| first_name | varchar(20) | yes | | null | |
| last_name | varchar(25) | no | | null | |
| email | varchar(100) | no | | null | |
| phone_number | varchar(20) | yes | | null | |
| hire_date | date | no | | null | |
| job_id | int(11) | no | mul | null | |
| salary | decimal(8,2) | no | | null | |
| manager_id | int(11) | yes | mul | null | |
| department_id | int(11) | yes | mul | null | |
+---------------+--------------+------+-----+---------+----------------+
10 rows in set
要查找没有电话号码的所有员工,请使用is null
运算符,如下所示:
要查找具有电话号码的所有员工,请使用is not null
,如以下语句所示:
select
employee_id,
first_name,
last_name,
phone_number
from
employees
where
phone_number is not null;
执行上面查询语句,得到以下结果 -
+-------------+------------+-----------+----------------+
| employee_id | first_name | last_name | phone_number |
+-------------+------------+-----------+----------------+
| 100 | steven | lee | 0532-86011111 |
| 101 | neena | wong | 0551-4243311 |
| 102 | lex | liang | 0571-87622362 |
| 103 | alexander | lee | 020-95105105 |
| 104 | bruce | wong | 0371-68356666 |
| 105 | david | liang | 0512-67513131 |
| 106 | valli | chen | 0535-95105175 |
| 107 | diana | chen | 025-95105105 |
| 108 | nancy | chen | 0531-86012520 |
| 109 | daniel | chen | 021-8008207890 |
... ...
| 201 | michael | zhou | 010-67237328 |
| 202 | pat | zhou | 0755-28114518 |
| 203 | susan | zhou | 0755-83587526 |
| 204 | hermann | wu | 0513-83512816 |
| 205 | shelley | wu | 0898-31686222 |
| 206 | william | wu | 022-26144822 |
+-------------+------------+-----------+----------------+
34 rows in set
通过本小节的学习,现在您应该了解null
概念并知道如何使用sql is null
运算符来检查值是否为null
值。