BEGIN; BEGIN EXPLAIN (ANALYZE, BUFFERS) select c_count, count(*) as custdist from ( select c_custkey, count(o_orderkey) from customer left outer join orders on c_custkey = o_custkey and o_comment not like '%pending%accounts%' group by c_custkey ) as c_orders (c_custkey, c_count) group by c_count order by custdist desc, c_count desc; QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=852463.69..852464.19 rows=200 width=8) (actual time=27213.656..27213.658 rows=46 loops=1) Sort Key: (count(*)), (count(orders.o_orderkey)) Sort Method: quicksort Memory: 27kB Buffers: shared hit=245130 read=45699 written=358 -> HashAggregate (cost=852454.05..852456.05 rows=200 width=8) (actual time=27213.589..27213.594 rows=46 loops=1) Group Key: count(orders.o_orderkey) Buffers: shared hit=245127 read=45699 written=358 -> HashAggregate (cost=814954.05..829954.05 rows=1500000 width=8) (actual time=26391.666..26881.670 rows=1500000 loops=1) Group Key: customer.c_custkey Buffers: shared hit=245127 read=45699 written=358 -> Hash Right Join (cost=69028.00..739656.33 rows=15059543 width=8) (actual time=1182.411..17081.065 rows=15338266 loops=1) Hash Cond: (orders.o_custkey = customer.c_custkey) Buffers: shared hit=245127 read=45699 written=358 -> Seq Scan on orders (cost=0.00..444735.19 rows=15059543 width=8) (actual time=0.017..6787.635 rows=14838250 loops=1) Filter: ((o_comment)::text !~~ '%pending%accounts%'::text) Rows Removed by Filter: 161750 Buffers: shared hit=245123 read=10425 written=339 -> Hash (cost=50278.00..50278.00 rows=1500000 width=4) (actual time=1172.608..1172.608 rows=1500000 loops=1) Buckets: 2097152 Batches: 1 Memory Usage: 69119kB Buffers: shared hit=4 read=35274 written=19 -> Seq Scan on customer (cost=0.00..50278.00 rows=1500000 width=4) (actual time=0.009..748.825 rows=1500000 loops=1) Buffers: shared hit=4 read=35274 written=19 Planning time: 2.615 ms Execution time: 27231.099 ms (24 rows) COMMIT; COMMIT