EXPLAIN ANALYZE SELECT o3.prodid, SUM(o3.opinion*o12.correlation) AS total_correlation FROM opinions o3 RIGHT JOIN ( SELECT o2.uid, SUM(o1.opinion*o2.opinion)/SQRT(count(*)+0.0) AS correlation FROM opinions o1 LEFT JOIN opinions o2 ON o1.prodid=o2.prodid WHERE o1.uid=1355 GROUP BY o2.uid ) o12 ON o3.uid=o12.uid LEFT JOIN ( SELECT o4.prodid, COUNT(*) as num_my_comments FROM opinions o4 WHERE o4.uid=1355 GROUP BY o4.prodid ) nmc ON o3.prodid=nmc.prodid WHERE nmc.num_my_comments IS NULL AND o3.opinion<>0 AND o12.correlation<>0 GROUP BY o3.prodid ORDER BY total_correlation desc; Sort (cost=10205.54..10205.54 rows=1889 width=36) (actual time=2468.23..2471.98 rows=7540 loops=1) -> Aggregate (cost=9960.51..10102.74 rows=1889 width=36) (actual time=1931.46..2420.30 rows=7540 loops=1) -> Group (cost=9960.51..10055.52 rows=18890 width=36) (actual time=1930.97..2307.68 rows=48789 loops=1) -> Merge Join (cost=9960.51..10008.29 rows=18890 width=36) (actual time=1930.96..2187.03 rows=48789 loops=1) -> Sort (cost=9637.85..9637.85 rows=18890 width=24) (actual time=1926.35..1960.59 rows=58792 loops=1) -> Merge Join (cost=3397.33..8296.13 rows=18890 width=24) (actual time=301.54..1467.33 rows=58792 loops=1) -> Index Scan using uid_index on opinions o3 (cost=0.00..4252.57 rows=92276 width=12) (actual time=0.28..700.61 rows=92276 loops=1) -> Sort (cost=3397.33..3397.33 rows=267 width=20) (actual time=301.12..350.30 rows=83792 loops=1) -> Subquery Scan o12 (cost=3353.13..3386.55 rows=267 width=20) (actual time=202.80..297.88 rows=1186 loops=1) -> Aggregate (cost=3353.13..3386.55 rows=267 width=20) (actual time=202.79..295.40 rows=1186 loops=1) -> Group (cost=3353.13..3359.82 rows=2674 width=20) (actual time=202.51..247.58 rows=13126 loops=1) -> Sort (cost=3353.13..3353.13 rows=2674 width=20) (actual time=202.50..210.04 rows=13126 loops=1) -> Nested Loop (cost=0.00..3200.95 rows=2674 width=20) (actual time=0.42..118.50 rows=13126 loops=1) -> Index Scan using uid_index on opinions o1 (cost=0.00..319.16 rows=90 width=8) (actual time=0.13..6.25 rows=216 loops=1) -> Index Scan using prodid_index on opinions o2 (cost=0.00..31.87 rows=23 width=12) (actual time=0.06..0.39 rows=61 loops=216) -> Sort (cost=322.66..322.66 rows=9 width=4) (actual time=4.41..10.46 rows=9989 loops=1) -> Subquery Scan nmc (cost=322.07..322.52 rows=9 width=4) (actual time=1.92..3.84 rows=216 loops=1) -> Aggregate (cost=322.07..322.52 rows=9 width=4) (actual time=1.90..3.43 rows=216 loops=1) -> Group (cost=322.07..322.29 rows=90 width=4) (actual time=1.88..2.57 rows=216 loops=1) -> Sort (cost=322.07..322.07 rows=90 width=4) (actual time=1.87..1.98 rows=216 loops=1) -> Index Scan using uid_index on opinions o4 (cost=0.00..319.16 rows=90 width=4) (actual time=0.09..1.35 rows=216 loops=1) Total runtime: 2510.04 msec