EXPLAIN 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 '%unusual%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=1815453.20..1815453.70 rows=200 width=8) Sort Key: (count(*)), (count(orders.o_orderkey)) -> HashAggregate (cost=1815443.56..1815445.56 rows=200 width=8) Group Key: count(orders.o_orderkey) -> GroupAggregate (cost=0.86..1792941.80 rows=1500117 width=8) Group Key: customer.c_custkey -> Merge Left Join (cost=0.86..1703692.26 rows=14849675 width=8) Merge Cond: (customer.c_custkey = orders.o_custkey) -> Index Only Scan using customer_pkey on customer (cost=0.43..74249.18 rows=1500117 width=4) -> Index Scan using i_o_custkey on orders (cost=0.43..1440100.49 rows=14849675 width=8) Filter: ((o_comment)::text !~~ '%unusual%packages%'::text) (11 rows)