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=927173.88..927174.38 rows=200 width=8) (actual time=67124.083..67124.086 rows=45 loops=1) Sort Key: (count(*)), (count(orders.o_orderkey)) Sort Method: quicksort Memory: 27kB Buffers: shared hit=285846 read=5742 dirtied=1 written=72 -> HashAggregate (cost=927164.24..927166.24 rows=200 width=8) (actual time=67123.945..67123.968 rows=45 loops=1) Buffers: shared hit=285843 read=5742 dirtied=1 written=72 -> HashAggregate (cost=889664.24..904664.24 rows=1500000 width=8) (actual time=65877.720..66791.097 rows=1500000 loops=1) Buffers: shared hit=285843 read=5742 dirtied=1 written=72 -> Hash Right Join (cost=69028.00..814748.21 rows=14983206 width=8) (actual time=1692.742..47629.203 rows=15338717 loops=1) Hash Cond: (orders.o_custkey = customer.c_custkey) Buffers: shared hit=285843 read=5742 dirtied=1 written=72 -> Seq Scan on orders (cost=0.00..446056.09 rows=14983206 width=8) (actual time=0.032..10152.226 rows=14838699 loops=1) Filter: ((o_comment)::text !~~ '%pending%packages%'::text) Rows Removed by Filter: 161301 Buffers: shared hit=250745 read=5562 dirtied=1 written=72 -> Hash (cost=50278.00..50278.00 rows=1500000 width=4) (actual time=1690.368..1690.368 rows=1500000 loops=1) Buckets: 262144 Batches: 1 Memory Usage: 52735kB Buffers: shared hit=35098 read=180 -> Seq Scan on customer (cost=0.00..50278.00 rows=1500000 width=4) (actual time=0.017..972.026 rows=1500000 loops=1) Buffers: shared hit=35098 read=180 Total runtime: 67164.432 ms (21 rows) COMMIT; COMMIT