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=1816986.85..1816987.35 rows=200 width=8) Sort Key: (count(*)), (count(orders.o_orderkey)) -> HashAggregate (cost=1816977.21..1816979.21 rows=200 width=8) Group Key: count(orders.o_orderkey) -> GroupAggregate (cost=0.86..1794475.45 rows=1500117 width=8) Group Key: customer.c_custkey -> Merge Left Join (cost=0.86..1705151.74 rows=14864508 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..1441374.66 rows=14864508 width=8) Filter: ((o_comment)::text !~~ '%unusual%packages%'::text) (11 rows)