sql - PostgreSQL - Query optimization on SUM and LEFT JOIN -
i'm taking month using to_char()
common in 2 tables namely table1
, table2
.
but in table2 have both date , month.
also i've created index on table1. if write same query table1 results within 1000ms.
i'm taking sum of values , combining results using left join.
here's query.
select "month", -- table2 sum("value1"), -- table2 sum("value2") -- table1 table2 left join table1 on table2."month" = to_char(table1.date, 'mon-yy') table2.date between '2014-01-01' , '2014-03-01' group "month"
explain of query :
"groupaggregate (cost=88133.61..3688425.12 rows=2 width=15)" " -> merge left join (cost=88133.61..2707006.48 rows=130855816 width=15)" " merge cond: (table2.month = (to_char((table1.date)::timestamp time zone, 'mon-yy'::text)))" " -> sort (cost=8922.32..9056.34 rows=53609 width=11)" " sort key: table2.month" " -> seq scan on table2(cost=0.00..3885.28 rows=53609 width=11)" " filter: ((date >= '2014-01-01'::date) , (date materialize (cost=79211.29..81652.22 rows=488186 width=8)" " -> sort (cost=79211.29..80431.75 rows=488186 width=8)" " sort key: (to_char((table1.date)::timestamp time zone, 'mon-yy'::text))" " -> seq scan on table1(cost=0.00..19735.86 rows=488186 width=8)"
currently have 500k rows in table1.
everyday update table around 3 4k records table1.
the query keeps running.
i no results.
can me i'm going wrong?
for query run 'efficiently', need 2 indexes. judging explain, table2 needs index on date column.
create index on table2 using btree(date);
table1 need computed index month name , day number e.g. "apr-14".
create index on table1 using btree(to_char(date, 'mon-yy'));
[edit, a_horse_with_no_name said not work because to_char not immutable - round writing own immutable function, simpler if stored date column!]
that said, text matching slower dates or numbers , if want order information alphabetical sort.
Comments
Post a Comment