When i am taking count(*)
from my base query it is taking more than 30 min to get the result.
instead of count(*)
, added '*' the query executed so fast. Here is the explain details.
base query :
explain
select -- QUERY 1
sec.ts,t.cnt
from
postgres.seconds sec
inner JOIN lateral
(
select count(*) as cnt
from postgres.query_execution query_exe
where sec.ts between query_exe.start_time and query_exe.end_time
) t on true where t.cnt > 0
explain plan details:
Nested Loop (cost=349.78..474530186.42 rows=1356481 width=16)
-> Seq Scan on seconds sec (cost=0.00..19567.81 rows=1356481 width=8)
-> Aggregate (cost=349.78..349.79 rows=1 width=8)
Filter: (count(*) > 0)
-> Seq Scan on query_execution query_exe (cost=0.00..347.00 rows=1111 width=
Filter: ((sec.ts >= start_time) AND (sec.ts <= end_time))
when i added count(*) ,
explain
select count(*) from ( -- added -- Query 2
select
sec.ts,t.cnt
from
schoolofit.seconds sec
inner JOIN lateral
(
select count(*) as cnt
from schoolofit.query_execution query_exe
where sec.ts between query_exe.start_time and query_exe.end_time
) t on true where t.cnt > 0) s;
----------------------------------------------------------------------------------------------+
Aggregate (cost=474533577.62..474533577.63 rows=1 width=8) |
-> Nested Loop (cost=349.78..474530186.42 rows=1356481 width=0) |
-> Seq Scan on seconds sec (cost=0.00..19567.81 rows=1356481 width=8) |
-> Aggregate (cost=349.78..349.79 rows=1 width=8) |
Filter: (count(*) > 0) |
-> Seq Scan on query_execution query_exe (cost=0.00..347.00 rows=1111 width=0)|
Filter: ((sec.ts >= start_time) AND (sec.ts <= end_time))
|
I could not find the reason why count(*) is taking more time. Is there any better approach to find the count. Please advise.
FYI .The base Query result count is 390269