SQL Server的非聚集索引中会存储NULL吗?
这是个很有意思的问题,下面通过如下的代码,来说明,到底会不会存储NULL。
-
--1.建表
-
if OBJECT_ID('t1') is not null
-
drop
table t1
-
go
-
-
create
table t1
-
(
-
id
int primary
key,
-
v
varchar(
20)
-
)
-
-
-
insert
into t1
-
select
1 ,
'aa'
union all
-
select
2 ,
'bb'
union all
-
select
3 ,
'cc'
union all
-
select
4 ,
'dd'
union all
-
select
5 ,
'ee'
union all
-
select
6 ,
'ff'
union all
-
select
7 ,
null
union all
-
select
8 ,
'gg'
union all
-
select
9 ,
null
-
go
-
-
-
--2.创建一个非聚集索引
-
create
index idx_t1_v
on t1(v)
-
go
-
-
-
--3.index_id = 2 为idx_t1_v索引
-
select *
-
from sys.indexes
-
where object_id = object_id(
't1')
-
-
-
--hobt_id = 72057594041466880
-
select *
-
from sys.partitions
-
where index_id =
2
-
and object_id = object_id(
't1')
-
-
-
--root_page = 0xAF0000000100
-
select *
-
from sys.system_internals_allocation_units
-
where container_id =
72057594041466880
-
-
-
-
--4.0100:文件id,而AF是16进制,转化为10进制是 175,pageId = 175
-
DBCC page(
12,
--数据库id : 10
-
1,
--文件id: 1
-
175,
--页id: 188
-
3)
--with tableresults
-
/*
-
文件id 页id 索引行号 层级 v列的值 这个v列值所对应的行号 id列的hash值
-
FileId PageId Row Level v (key) id (key) KeyHashValue
-
1 175 0 0 NULL 7 (8d4dc9cd25b3)
-
1 175 1 0 NULL 9 (fd07a7dffc59)
-
1 175 2 0 aa 1 (e5e354933dff)
-
1 175 3 0 bb 2 (df47e5a393e1)
-
1 175 4 0 cc 3 (36248ab30914)
-
1 175 5 0 dd 4 (40ee14f42575)
-
1 175 6 0 ee 5 (a98d7be4bf80)
-
1 175 7 0 ff 6 (9329cad4119e)
-
1 175 8 0 gg 8 (f34ca041b78d)
-
*/
-
-
-
-
--5.走的索引查找
-
select *
-
from t1
-
where v
is
null
-
-
-
--走的是索引扫描,之所以这里走索引,是因为在v列的非聚集索引中,也包含了所有的数据
-
select *
-
from t1
-
where v
like
'%a%'
从第4个输出,可以看出非聚集索引中是存储了NULL的。