MYSQL数据库NULL和空值实验

create table test_null (
cola varchar(255) not null,
colb varchar(255) default null
) engine=innodb default charset=utf8;

(root:)[test]> show create table test_null\G
*************************** 1. row ***************************
       Table: test_null
Create Table: CREATE TABLE `test_null` (
  `colA` varchar(255) NOT NULL,
  `colB` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

insert into `test_null`(`cola`, `colb`) values (null, null);

(root:)[test]> insert into `test_null`(`cola`, `colb`) values (null, null);
ERROR 1048 (23000): Column 'colA' cannot be null


--插入空值
insert into `test_null`(`cola`, `colb`) values ('', '');

(root:)[test]> select * from test_null;
+------+------+
| colA | colB |
+------+------+
|      |      |
+------+------+
1 row in set (0.00 sec)

insert into `test_null`(`cola`, `colb`) values ('1', '2');
insert into `test_null`(`cola`) values ('1');


(root:)[test]> select * from test_null;
+------+------+
| colA | colB |
+------+------+
|      |      |
| 1    | 2    |
| 1    | NULL |
+------+------+
3 rows in set (0.00 sec)


select * from `test_null` where cola is not null;


(root:)[test]> select * from `test_null` where cola is not null;
+------+------+
| colA | colB |
+------+------+
|      |      |
| 1    | 2    |
| 1    | NULL |
+------+------+
3 rows in set (0.00 sec)


select * from `test_null` where colb is not null;

(root:)[test]> select * from `test_null` where colb is not null;
+------+------+
| colA | colB |
+------+------+
|      |      |
| 1    | 2    |
+------+------+
2 rows in set (0.00 sec)

结论:使用 IS NOT NULL 查询不会过滤空值,但是会过滤掉NULL。

select * from `test_null` where cola <> '';

(root:)[test]> select * from `test_null` where colb <> '';
+------+------+
| colA | colB |
+------+------+
| 1    | 2    |
+------+------+
1 row in set (0.00 sec)

结论:使用 <> 会过滤掉NULL和空值。

select count(colb) from `test_null`;

(root:)[test]> select count(colb) from `test_null`;
+-------------+
| count(colb) |
+-------------+
|           2 |
+-------------+
1 row in set (0.01 sec)


结论:使用 count 会过滤掉 NULL 值,但是不会过滤掉空值。


总结
1、空值不占空间,NULL值占空间(占用一个字节)。
2、当字段不为NULL时,也可以插入空值。
3、当使用 IS NOT NULL 或者 IS NULL 时,只能查出字段中没有不为NULL的或者为 NULL 的,不能查出空值。
4、使用 <> 查询时,会筛选掉空值和NULL值。
5、使用 count 统计时会过滤掉 NULL 值,但是不会过滤掉空值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

#慧#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值