【发布时间】:2021-01-02 12:05:43
【问题描述】:
我是索引概念的新手,但我正试图弄清楚它是如何工作的。
我想提高以下查询的性能。
explain analyze select to_char(rental_date, 'month') as month, count(*) count
from rental
join instrument on rental.instrument_id = instrument.instrument_id
where extract(year from rental_date) = 2020
group by month, extract(month from rental_date)
order by extract(month from rental_date) asc
;
执行计划
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
GroupAggregate (cost=75.10..75.55 rows=15 width=48) (actual time=14.204..14.821 rows=12 loops=1)
Group Key: (date_part('month'::text, (rental.rental_date)::timestamp without time zone)), (to_char((rental.rental_date)::timestamp with time zone, 'month'::text))
-> Sort (cost=75.10..75.14 rows=15 width=40) (actual time=14.121..14.298 rows=1540 loops=1)
Sort Key: (date_part('month'::text, (rental.rental_date)::timestamp without time zone)), (to_char((rental.rental_date)::timestamp with time zone, 'month'::text))
Sort Method: quicksort Memory: 169kB
-> Hash Join (cost=1.20..74.81 rows=15 width=40) (actual time=7.912..13.166 rows=1540 loops=1)
Hash Cond: (rental.instrument_id = instrument.instrument_id)
-> Seq Scan on rental (cost=0.00..73.39 rows=15 width=8) (actual time=0.061..2.027 rows=1540 loops=1)
Filter: (date_part('year'::text, (rental_date)::timestamp without time zone) = '2020'::double precision)
Rows Removed by Filter: 1511
-> Hash (cost=1.09..1.09 rows=9 width=4) (actual time=0.046..0.047 rows=9 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 9kB
-> Seq Scan on instrument (cost=0.00..1.09 rows=9 width=4) (actual time=0.012..0.016 rows=9 loops=1)
Planning Time: 3.908 ms
Execution Time: 15.072 ms
(15 rows)
我的想法是在instrument_id 和rental_date 上建立索引,因为intrument_id 是外键,而rental_date 在where 子句中。
create index isx_rental ON rental(instrument_id);
create index isx_date ON rental(rental_date);
但这根本不影响运行时。
为什么这对我的性能没有帮助?
【问题讨论】:
-
15 毫秒秒似乎很快。你需要多快?
标签: postgresql indexing