简体   繁体   English

使用索引改进使用 Seq Scan 的查询

[英]Improve query that uses Seq Scan using indexes

I'm trying to optimize this query.我正在尝试优化此查询。 It's doing Sequential Scan, which grows linear to number of rows.它正在执行顺序扫描,它与行数呈线性增长。

SELECT "class"."starts_at"
FROM "class"
WHERE ("class"."starts_at" >= 2021-12-16 14:13:19.824533+00:00
       AND "class"."starts_at" BETWEEN 2021-12-01 00:00:00+05:00 AND 2021-12-31 23:59:59+05:00
       AND "class"."status" = reserved
       AND "class"."teacher_id" = 3)

Query PlanSeq Scan on class  (cost=0.00..1.18 rows=1 width=8) (actual time=0.029..0.056 rows=1 loops=1)
  Filter: ((starts_at >= '2021-12-16 14:13:19.824533+00'::timestamp with time zone) AND (starts_at >= '2021-11-30 19:00:00+00'::timestamp with time zone) AND (starts_at <= '2021-12-31 18:59:59+00'::timestamp with time zone) AND ((status)::text = 'reserved'::text) AND (teacher_id = 3))
  Rows Removed by Filter: 7
Planning Time: 0.138 ms
Execution Time: 0.138 ms

When I add index for starts_at , status , and teacher , it's not using the index.当我为starts_atstatusteacher添加索引时,它没有使用索引。

BEGIN;
--
-- Create index starts_at_status_teacher_idx on field(s) starts_at, status, teacher of model class
--
CREATE INDEX "starts_at_status_teacher_idx" ON "class" ("starts_at", "status", "teacher_id");
COMMIT;

What index do I need to add to make it faster?我需要添加什么索引以使其更快?

Your index should be:您的索引应该是:

CREATE INDEX X0001 ON "class" (teacher_id, status, starts_at);

When you have inequality and equality in a predicate, you must set the columns with equality first in the index key and the inequality columns at last...当谓词中存在不等式和相等性时,必须首先在索引键中设置相等的列,最后设置不等式列...

If you had executed this query in Microsoft SQL Server, the optimizer would have gave you the correct index in the right order of columns in the key...如果您在 Microsoft SQL 服务器中执行了此查询,优化器会按照键中列的正确顺序为您提供正确的索引...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM