← 中文资源

简体中文版本

用 EXPLAIN 检查索引使用

阅读 EXPLAIN 执行计划,确认查询是否使用预期索引以及顺序扫描或排序出现在何处。

阅读英文原文

实现说明

实际执行的是 SELECT / EXPLAIN——涉及的对象是 users。 逐子句看,这些语句使用了:WHERE 把语句的作用范围收窄到满足条件的行;ORDER BY 固定了输出顺序;LIMIT 限制返回行数。

常见问题

这里涉及哪些关系(表/CTE)?

引用的是 users。

核心语句

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, email
FROM users
WHERE tenant_id = 42
  AND created_at >= now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50;

代码示例

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, email
FROM users
WHERE tenant_id = 42
  AND created_at >= now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50;

-- A covering index such as (tenant_id, created_at DESC) lets the planner
-- use an index scan and avoid a sort when the ORDER BY matches the index.