☰
supabase-postgres-best-practices - query-covering-indexes
2026/10/13 12:42:03 网站建设 项目流程

title: Use Covering Indexes to Avoid Table Lookups
impact: MEDIUM-HIGH
impactDescription: 2-5x faster queries by eliminating heap fetches
tags: indexes, covering-index, include, index-only-scan

使用覆盖索引避免回表查询

覆盖索引包含查询所需的全部列,从而支持索引扫描而无需访问表本身。

错误做法(索引扫描 + 堆表取数):

createindexusers_email_idxonusers(email);-- 必须从表堆中获取 name 和 created_atselectemail,name,created_atfromuserswhereemail='user@example.com';

正确做法(使用 INCLUDE 的索引扫描):

-- 将不可用于搜索的列包含在索引中createindexusers_email_idxonusers(email)include(name,created_at);-- 所有列都由索引提供,无需访问表selectemail,name,created_atfromuserswhereemail='user@example.com';

对于 SELECT 中需要但不需要过滤的列,使用 INCLUDE:

-- 按 status 搜索,但还需要 customer_id 和 totalcreateindexorders_status_idxonorders(status)include(customer_id,total);selectstatus,customer_id,totalfromorderswherestatus='shipped';

参考:仅索引扫描

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询