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%packages%' 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=847674.39..847674.89 rows=200 width=8) (actual time=35220.446..35220.446 rows=46 loops=1) Sort Key: (count(*)), (count(orders.o_orderkey)) Sort Method: quicksort Memory: 27kB Buffers: shared hit=253020 read=37302 written=1086 -> HashAggregate (cost=847664.75..847666.75 rows=200 width=8) (actual time=35220.342..35220.353 rows=46 loops=1) Group Key: count(orders.o_orderkey) Buffers: shared hit=253017 read=37302 written=1086 -> HashAggregate (cost=810164.75..825164.75 rows=1500000 width=8) (actual time=34389.365..34892.070 rows=1500000 loops=1) Group Key: customer.c_custkey Buffers: shared hit=253017 read=37302 written=1086 -> Hash Right Join (cost=69028.00..735843.77 rows=14864195 width=8) (actual time=1082.703..20916.598 rows=15353590 loops=1) Hash Cond: (orders.o_custkey = customer.c_custkey) Buffers: shared hit=253017 read=37302 written=1086 -> Seq Scan on orders (cost=0.00..443852.85 rows=14864195 width=8) (actual time=0.029..8057.550 rows=14853572 loops=1) Filter: ((o_comment)::text !~~ '%pending%packages%'::text) Rows Removed by Filter: 161428 Buffers: shared hit=217739 read=37302 written=1086 -> Hash (cost=50278.00..50278.00 rows=1500000 width=4) (actual time=1066.343..1066.343 rows=1500000 loops=1) Buckets: 2097152 Batches: 1 Memory Usage: 69119kB Buffers: shared hit=35278 -> Seq Scan on customer (cost=0.00..50278.00 rows=1500000 width=4) (actual time=0.017..535.456 rows=1500000 loops=1) Buffers: shared hit=35278 Planning time: 3.065 ms Execution time: 35252.469 ms (24 rows) COMMIT; COMMIT