1

Таблица содержит более 100 миллионов строк (PostgreSQL 13.1)

CREATE TABLE report
(
    id     serial primary key,
    license_plate_id integer,
    datetime timestamp
);

Индексы (для теста я создал оба):

create index report_lp_datetime_index on report (license_plate_id, datetime);
create index report_lp_datetime_desc_index on report (license_plate_id desc, datetime desc);

Почему такой запрос очень медленный (~10 секунд):

select * from report r
where r.license_plate_id in (1,2,4,5,6,7,8,10,15,22,34,75)
order by datetime desc
limit 100

А запрос без использования order выполняется быстро (миллисекунды).

Explain:

explain (analyze, buffers, format text) select * from report r
where r.license_plate_id in (1,2,4,5,6,7,8,10,15,22,34, 75,374,57123)
limit 100
Limit  (cost=0.57..400.38 rows=100 width=316) (actual time=0.037..0.216 rows=100 loops=1)
  Buffers: shared hit=103
  ->  Index Scan using report_lp_id_idx on report r  (cost=0.57..44986.97 rows=11252 width=316) (actual time=0.035..0.202 rows=100 loops=1)
        Index Cond: (license_plate_id = ANY ('{1,2,4,5,6,7,8,10,15,22,34,75,374,57123}'::integer[]))
        Buffers: shared hit=103
Planning Time: 0.228 ms
Execution Time: 0.251 ms


explain (analyze, buffers, format text) select * from report r
where r.license_plate_id in (1,2,4,5,6,7,8,10,15,22,34,75,374,57123)
order by datetime desc
limit 100
Limit  (cost=44193.63..44193.88 rows=100 width=316) (actual time=4921.030..4921.047 rows=100 loops=1)
  Buffers: shared hit=11455 read=671
  ->  Sort  (cost=44193.63..44221.76 rows=11252 width=316) (actual time=4921.028..4921.035 rows=100 loops=1)
        Sort Key: datetime DESC
        Sort Method: top-N heapsort  Memory: 128kB
        Buffers: shared hit=11455 read=671
        ->  Bitmap Heap Scan on report r  (cost=151.18..43763.59 rows=11252 width=316) (actual time=54.422..4911.927 rows=12148 loops=1)
              Recheck Cond: (license_plate_id = ANY ('{1,2,4,5,6,7,8,10,15,22,34,75,374,57123}'::integer[]))
              Heap Blocks: exact=12063
              Buffers: shared hit=11455 read=671
              ->  Bitmap Index Scan on report_lp_id_idx  (cost=0.00..148.37 rows=11252 width=0) (actual time=52.631..52.632 rows=12148 loops=1)
                    Index Cond: (license_plate_id = ANY ('{1,2,4,5,6,7,8,10,15,22,34,75,374,57123}'::integer[]))
                    Buffers: shared hit=59 read=4
Planning Time: 0.427 ms
Execution Time: 4921.128 ms

UPD: Без limit:

explain (analyze, buffers, format text) select * from report r
where r.license_plate_id in (1,2,4,5,6,7,8,10,15,22,34,75,374,57123)
order by datetime desc
Sort  (cost=44520.73..44548.86 rows=11252 width=316) (actual time=47069.334..47072.201 rows=12148 loops=1)
  Sort Key: datetime DESC
  Sort Method: external merge  Disk: 3936kB
  Buffers: shared hit=1235 read=10891, temp read=492 written=493
  ->  Bitmap Heap Scan on report r  (cost=151.18..43763.59 rows=11252 width=316) (actual time=35.437..47019.934 rows=12148 loops=1)
        Recheck Cond: (license_plate_id = ANY ('{1,2,4,5,6,7,8,10,15,22,34,75,374,57123}'::integer[]))
        Heap Blocks: exact=12063
        Buffers: shared hit=1235 read=10891
        ->  Bitmap Index Scan on report_lp_id_idx  (cost=0.00..148.37 rows=11252 width=0) (actual time=33.662..33.662 rows=12148 loops=1)
              Index Cond: (license_plate_id = ANY ('{1,2,4,5,6,7,8,10,15,22,34,75,374,57123}'::integer[]))
              Buffers: shared hit=59 read=4
Planning Time: 0.269 ms
Execution Time: 47073.630 ms
1
  • Это русскоязычный stackoverflow и вопросы и ответы должны быть на русском языке
    – Mike
    31 янв 2021 в 13:22

1 ответ 1

0

Потому что postgres-у надо отсортировать 11252 записей. И не только: postgres должен получить все записи, удовлетворяющие условию в WHERE.

Без ORDER BY postgres знает LIMIT и ему не надо получать все подходящие записи: любых ста, удовлетворяющих условию, достаточно (берутся первые подходящие). Также без LIMIT первый SELECT может выполняться быстрее второго из-за того, что ему не надо сортировать результат. Сортировка имеет цену ( O(n*log n) ).

6
  • I am updated the question. Query without LIMIT is slow too.
    – Alexey
    31 янв 2021 в 13:03
  • It is right, without limit is worst, because the same reason. It must fetch 11252 records and sort them. Ok, this is a little distinct question, I update my answer... 31 янв 2021 в 13:19
  • Это русскоязычный stackoverflow и вопросы и ответы должны быть на русском языке
    – Mike
    31 янв 2021 в 13:22
  • Uh can you please translate your answer into Russian? Thanks ;) 31 янв 2021 в 13:26
  • Вы правы. Я ответил на английском, потому что вопрос был на английском. Русский не мой родной язык, я думаю, что любой, даже Google может сделать перевод лучше меня. 31 янв 2021 в 15:20

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.