Как заставить postgres использовать индекс в запросе?
После переноса данных из postgres 10 в postgres 14 один и тот-же запрос стал выполняться в 2000 раз дольше.
PostgreSQL 10.7
Запрос выполняется 34ms, считается сумма транзакций за 5 минут. Тут все ок время устраивает.
SELECT sum(amount) sum, max(id) max
FROM t_transaction
WHERE id > (select max(id)-1000 from t_transaction)
AND ( created_at > '2021-12-13T16:15:00.000Z'
AND created_at <= '2021-12-13T16:20:00.000Z');
Перенесли БД в PostgreSQL 14.1 запрос тот-же, но выполняется уже 95421.923 ms, это очень долго. Видно что индекс не используется вообще.
explain analyze SELECT sum(amount) sum, max(id) max FROM t_transaction WHERE id > (select max(id)-1000 from t_transaction) AND (created_at > '2021-12-13T16:15:00.000Z' AND created_at <= '2021-12-13T16:20:00.000Z');
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=8044103.05..8044103.06 rows=1 width=36) (actual time=95301.993..95307.927 rows=1 loops=1)
InitPlan 2 (returns $1)
-> Result (cost=0.60..0.61 rows=1 width=4) (actual time=378.417..378.420 rows=1 loops=1)
InitPlan 1 (returns $0)
-> Limit (cost=0.57..0.60 rows=1 width=4) (actual time=0.127..0.128 rows=1 loops=1)
-> Index Only Scan Backward using t_transaction_pkey on t_transaction t_transaction_1 (cost=0.57..13762186.97 rows=483433280 width=4) (actual time=0.117..0.117 rows=1 loops=1)
Index Cond: (id IS NOT NULL)
Heap Fetches: 0
-> Gather (cost=1000.00..8044102.43 rows=1 width=12) (actual time=95301.967..95307.898 rows=0 loops=1)
Workers Planned: 2
Params Evaluated: $1
Workers Launched: 2
-> Parallel Seq Scan on t_transaction (cost=0.00..8043102.33 rows=1 width=12) (actual time=94867.425..94867.425 rows=0 loops=3)
Filter: ((id > $1) AND (created_at > '2021-12-13 16:15:00'::timestamp without time zone) AND (created_at <= '2021-12-13 16:20:00'::timestamp without time zone))
Rows Removed by Filter: 161144405
Planning Time: 49.518 ms
JIT:
Functions: 21
Options: Inlining true, Optimization true, Expressions true, Deforming true
Timing: Generation 4.629 ms, Inlining 421.424 ms, Optimization 96.794 ms, Emission 61.828 ms, Total 584.676 ms
Execution Time: 95421.923 ms
(21 rows)
Пробовал делать ANALYZE t_transaction, результата не дало.
Индекс в таблице есть.
\d t_transaction
Table "public.t_transaction"
Column | Type | Collation | Nullable | Default
-------------+-----------------------------+-----------+----------+-------------------------------------------
id | integer | | not null | nextval('t_transaction_id_seq'::regclass)
from_id | integer | | not null |
to_id | integer | | not null |
amount | bigint | | not null |
type | smallint | | not null |
created_at | timestamp without time zone | | not null |
external_id | integer | | not null |
payload | integer | | not null |
Indexes:
"t_transaction_pkey" PRIMARY KEY, btree (id)