1

This query take 2s to done:

explain analyze select
    *
from
    "MdChapters" as "MdChapter" 
where
    ("MdChapter"."countryCode" = 'gb' AND "MdChapter"."deletedAt" is  null)
order by
    "MdChapter"."id" desc 
limit 100;
Limit  (cost=56.35..56.38 rows=13 width=2656) (actual time=1854.038..1854.409 rows=100 loops=1)
  ->  Sort  (cost=56.35..56.38 rows=13 width=2656) (actual time=1854.035..1854.163 rows=100 loops=1)
        Sort Key: id DESC
        Sort Method: top-N heapsort  Memory: 150kB
        ->  Bitmap Heap Scan on "MdChapters" "MdChapter"  (cost=4.56..56.10 rows=13 width=2656) (actual time=49.818..1355.082 rows=327179 loops=1)
              Recheck Cond: ((("countryCode")::text = 'gb'::text) AND ("deletedAt" IS NULL))
              Heap Blocks: exact=47298
              ->  Bitmap Index Scan on test  (cost=0.00..4.55 rows=13 width=0) (actual time=42.630..42.632 rows=328948 loops=1)
                    Index Cond: ((("countryCode")::text = 'gb'::text) AND ("deletedAt" IS NULL))
Planning time: 0.200 ms
Execution time: 1854.567 ms

But this query just take < 0.1s:

select
    *
from
    "MdChapters" as "MdChapter" 
where
    ("MdChapter"."countryCode" = 'gb')
order by
    "MdChapter"."id" desc 
limit 100;

I have indexes on both colum countryCode and deletedAt

CREATE INDEX md_chapters_deleted_at_country_code ON public."MdChapters" USING btree ("deletedAt", "countryCode");

1 Answer 1

1

I would create filtered/parial index:

CREATE INDEX md_chapters_deleted_at_country_code2 ON public."MdChapters" 
USING btree ("countryCode", "id")
WHERE ("deletedAt" IS NULL);
Sign up to request clarification or add additional context in comments.

10 Comments

Not work for me, this is Explain result: explain.depesz.com/s/gpgJ
Let's try adding id: CREATE INDEX md_chapters_deleted_at_country_code2 ON public."MdChapters" USING btree ("countryCode", "id") WHERE ("deletedAt" IS NULL);
Thanks a lot, its work now :). Now it just takes 0.6ms explain.depesz.com/s/Zt7b
When you are creating covering index you should start with columns that are used for filtering i.e. country_coude, then deteledAt and finally id. I am not sure if PostgreSQL supports index skip column scan.
You should open a new question for the other problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.