BEGIN; BEGIN EXPLAIN (ANALYZE, BUFFERS) 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 ('17', '32', '29', '12', '22', '26', '13') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('17', '32', '29', '12', '22', '26', '13') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=691171.47..691171.48 rows=3 width=20) (actual time=10813.480..10813.480 rows=7 loops=1) Sort Key: (substr((public.customer.c_phone)::text, 1, 2)) Sort Method: quicksort Memory: 25kB Buffers: shared hit=323980 read=1596 InitPlan 1 (returns $0) -> Aggregate (cost=52888.75..52888.76 rows=1 width=4) (actual time=469.006..469.006 rows=1 loops=1) Buffers: shared hit=35286 read=1057 -> Bitmap Heap Scan on customer (cost=6642.54..51934.99 rows=381503 width=4) (actual time=93.905..393.562 rows=381680 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{17,32,29,12,22,26,13}'::text[])) AND (c_acctbal > 0::double precision)) Buffers: shared hit=35286 read=1057 -> Bitmap Index Scan on customer_c_phone_idx_c_acctbal (cost=0.00..6547.16 rows=381503 width=0) (actual time=85.601..85.601 rows=381680 loops=1) Index Cond: (substr((c_phone)::text, 1, 2) = ANY ('{17,32,29,12,22,26,13}'::text[])) Buffers: shared hit=8 read=1057 -> HashAggregate (cost=638282.64..638282.69 rows=3 width=20) (actual time=10813.406..10813.407 rows=7 loops=1) Buffers: shared hit=323978 read=1596 -> Hash Anti Join (cost=594267.99..637836.78 rows=59449 width=20) (actual time=10393.548..10792.909 rows=63463 loops=1) Hash Cond: (public.customer.c_custkey = orders.o_custkey) Buffers: shared hit=323978 read=1596 -> Bitmap Heap Scan on customer (cost=2908.85..41861.59 rows=139990 width=24) (actual time=522.283..673.313 rows=190758 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{17,32,29,12,22,26,13}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=70453 read=1596 -> Bitmap Index Scan on customer_c_phone_idx (cost=0.00..2873.86 rows=139990 width=0) (actual time=515.079..515.079 rows=190758 loops=1) Index Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{17,32,29,12,22,26,13}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=35295 read=1596 -> Hash (cost=403671.84..403671.84 rows=15014984 width=4) (actual time=9856.183..9856.183 rows=15015000 loops=1) Buckets: 2097152 Batches: 1 Memory Usage: 527872kB Buffers: shared hit=253522 -> Seq Scan on orders (cost=0.00..403671.84 rows=15014984 width=4) (actual time=0.019..4414.335 rows=15015000 loops=1) Buffers: shared hit=253522 Total runtime: 10932.393 ms (30 rows) COMMIT; COMMIT