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 '%express%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=849747.55..849748.05 rows=200 width=8) (actual time=31907.152..31907.157 rows=46 loops=1) Sort Key: (count(*)), (count(orders.o_orderkey)) Sort Method: quicksort Memory: 27kB Buffers: shared hit=278541 read=12288 written=31 -> HashAggregate (cost=849737.91..849739.91 rows=200 width=8) (actual time=31907.057..31907.068 rows=46 loops=1) Group Key: count(orders.o_orderkey) Buffers: shared hit=278538 read=12288 written=31 -> HashAggregate (cost=812237.91..827237.91 rows=1500000 width=8) (actual time=30958.526..31602.157 rows=1500000 loops=1) Group Key: customer.c_custkey Buffers: shared hit=278538 read=12288 written=31 -> Hash Right Join (cost=69028.00..737619.23 rows=14923736 width=8) (actual time=930.098..18978.817 rows=15338952 loops=1) Hash Cond: (orders.o_custkey = customer.c_custkey) Buffers: shared hit=278538 read=12288 written=31 -> Seq Scan on orders (cost=0.00..444735.19 rows=14923736 width=8) (actual time=0.027..7690.246 rows=14838934 loops=1) Filter: ((o_comment)::text !~~ '%express%accounts%'::text) Rows Removed by Filter: 161066 Buffers: shared hit=243260 read=12288 written=31 -> Hash (cost=50278.00..50278.00 rows=1500000 width=4) (actual time=917.823..917.823 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.011..457.321 rows=1500000 loops=1) Buffers: shared hit=35278 Planning time: 2.235 ms Execution time: 31926.025 ms (24 rows) COMMIT; COMMIT