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=852120.87..852121.37 rows=200 width=8) (actual time=47547.039..47547.042 rows=46 loops=1) Sort Key: (count(*)), (count(orders.o_orderkey)) Sort Method: quicksort Memory: 27kB Buffers: shared hit=275919 read=15416 written=44 -> HashAggregate (cost=852111.23..852113.23 rows=200 width=8) (actual time=47546.896..47546.907 rows=46 loops=1) Group Key: count(orders.o_orderkey) Buffers: shared hit=275916 read=15416 written=44 -> HashAggregate (cost=814611.23..829611.23 rows=1500000 width=8) (actual time=46260.471..47205.973 rows=1500000 loops=1) Group Key: customer.c_custkey Buffers: shared hit=275916 read=15416 written=44 -> Hash Right Join (cost=69028.00..739619.37 rows=14998372 width=8) (actual time=1148.892..27079.028 rows=15353127 loops=1) Hash Cond: (orders.o_custkey = customer.c_custkey) Buffers: shared hit=275916 read=15416 written=44 -> Seq Scan on orders (cost=0.00..445615.79 rows=14998372 width=8) (actual time=0.029..8258.989 rows=14853111 loops=1) Filter: ((o_comment)::text !~~ '%pending%accounts%'::text) Rows Removed by Filter: 161889 Buffers: shared hit=242313 read=13741 written=43 -> Hash (cost=50278.00..50278.00 rows=1500000 width=4) (actual time=1134.469..1134.469 rows=1500000 loops=1) Buckets: 2097152 Batches: 1 Memory Usage: 69119kB Buffers: shared hit=33603 read=1675 written=1 -> Seq Scan on customer (cost=0.00..50278.00 rows=1500000 width=4) (actual time=0.022..649.662 rows=1500000 loops=1) Buffers: shared hit=33603 read=1675 written=1 Planning time: 4.484 ms Execution time: 48079.241 ms (24 rows) COMMIT; COMMIT