BEGIN; BEGIN 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 ('26', '34', '27', '17', '30', '29', '21') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('26', '34', '27', '17', '30', '29', '21') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------ Sort (cost=691159.14..691159.15 rows=3 width=20) Sort Key: (substr((public.customer.c_phone)::text, 1, 2)) InitPlan 1 (returns $0) -> Aggregate (cost=52868.90..52868.91 rows=1 width=4) -> Bitmap Heap Scan on customer (cost=6638.36..51916.51 rows=380958 width=4) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{26,34,27,17,30,29,21}'::text[])) AND (c_acctbal > 0::double precision)) -> Bitmap Index Scan on customer_c_phone_idx_c_acctbal (cost=0.00..6543.12 rows=380958 width=0) Index Cond: (substr((c_phone)::text, 1, 2) = ANY ('{26,34,27,17,30,29,21}'::text[])) -> HashAggregate (cost=638290.16..638290.21 rows=3 width=20) -> Hash Anti Join (cost=594266.92..637850.98 rows=58557 width=20) Hash Cond: (public.customer.c_custkey = orders.o_custkey) -> Bitmap Heap Scan on customer (cost=2907.78..41857.76 rows=139885 width=24) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{26,34,27,17,30,29,21}'::text[])) AND (c_acctbal > $0)) -> Bitmap Index Scan on customer_c_phone_idx (cost=0.00..2872.81 rows=139885 width=0) Index Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{26,34,27,17,30,29,21}'::text[])) AND (c_acctbal > $0)) -> Hash (cost=403671.84..403671.84 rows=15014984 width=4) -> Seq Scan on orders (cost=0.00..403671.84 rows=15014984 width=4) (17 rows) COMMIT; COMMIT