(Postgres)回答“为空”或“不为空”问题的索引

问题描述 投票:0回答:1

由于历史原因,我有一个表,其中有一列可以为空

timestamp
。然而,随着代码多年来的进步,我们基本上最终将其视为布尔值:基本上,
is null
is not null

有没有办法可以为此列建立索引以加速对此列的

is null
is not null
查询?

我尝试过的一件事是:

create index <name> on <table> ((<column> is null))

这似乎适用于

is null
查询。但是,postgres 似乎没有将此索引用于
is not null
查询,即使我尝试使用一些笨拙的语法(如
where (<column> is null) = false
)来强制它。

在有人提出建议之前:是的,我知道我们应该将该列更改为布尔值,但是有大量代码使用它,包括无法更改的旧客户端,因为客户无法更改否则不会升级🤷

postgresql indexing
1个回答
0
投票

create index <name> on <table> ((<column> is not null))

或者您可以将其设为部分索引:

create index <name> on <table> (some_other_colum) where <column> is not null

我不认为可以构建单个 btree 索引来加速这两个查询。但由于 IS NULL 条件和 IS NOT NULL 条件不能同时具有高选择性,因此索引很可能只能对其中一种情况有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.