EXPLAIN select cntrycode, count(*) as numcust, sum(c_acctbal) as totacctbal from ( select substr(c_phone, 1, 2) as cntrycode, c_acctbal from customer where substr(c_phone, 1, 2) in ('13', '17', '26', '27', '29', '32', '28') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('13', '17', '26', '27', '29', '32', '28') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------ GroupAggregate (cost=229480.41..229668.73 rows=7533 width=20) Group Key: (substr((customer.c_phone)::text, 1, 2)) InitPlan 1 (returns $0) -> Aggregate (cost=74781.35..74781.36 rows=1 width=4) -> Seq Scan on customer customer_1 (cost=0.00..74662.07 rows=47709 width=4) Filter: ((c_acctbal > 0::double precision) AND (substr((c_phone)::text, 1, 2) = ANY ('{13,17,26,27,29,32,28}'::text[]))) -> Sort (cost=154699.05..154717.88 rows=7533 width=20) Sort Key: (substr((customer.c_phone)::text, 1, 2)) -> Nested Loop Anti Join (cost=0.43..154213.96 rows=7533 width=20) -> Seq Scan on customer (cost=0.00..74662.07 rows=17501 width=24) Filter: ((c_acctbal > $0) AND (substr((c_phone)::text, 1, 2) = ANY ('{13,17,26,27,29,32,28}'::text[]))) -> Index Only Scan using i_o_custkey on orders (cost=0.43..48.44 rows=18 width=4) Index Cond: (o_custkey = customer.c_custkey) (13 rows)