## 使用部分索引进行过滤查询
部分索引仅包含符合 WHERE 条件的行,当查询始终基于相同条件进行过滤时,这会使索引更小、速度更快。
**错误示范(全量索引包含无关行):**
sql
-- 索引包含所有行,甚至是已软删除的行
create index users_email_idx on users (email);
-- 查询始终过滤活跃用户
select * from users where email = '
[email protected]' and deleted_at is null;
**正确示范(部分索引匹配查询过滤条件):**
sql
-- 索引仅包含活跃用户
create index users_active_email_idx on users (email)
where deleted_at is null;
-- 查询使用更小、更快的索引
select * from users where email = '
[email protected]' and deleted_at is null;
部分索引的常见用例:
sql
-- 仅针对待处理订单(一旦完成,状态很少改变)
create index orders_pending_idx on orders (created_at)
where status = 'pending';
-- 仅针对非空值
create index products_sku_idx on products (sku)
where sku is not null;
参考:[部分索引 (Partial Indexes)](https://www.postgresql.org/docs/current/indexes-partial.html)