简体   繁体   中英

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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