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 ('27', '21', '33', '15', '18', '26', '12') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('27', '21', '33', '15', '18', '26', '12') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; QUERY PLAN -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=690679.77..690679.78 rows=3 width=20) (actual time=9220.180..9220.181 rows=7 loops=1) Sort Key: (substr((public.customer.c_phone)::text, 1, 2)) Sort Method: quicksort Memory: 25kB Buffers: shared hit=324007 read=1598 InitPlan 1 (returns $0) -> Aggregate (cost=52950.19..52950.20 rows=1 width=4) (actual time=429.521..429.522 rows=1 loops=1) Buffers: shared hit=35286 read=1059 -> Bitmap Heap Scan on customer (cost=6674.51..51993.87 rows=382528 width=4) (actual time=79.808..356.839 rows=382464 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{27,21,33,15,18,26,12}'::text[])) AND (c_acctbal > 0::double precision)) Buffers: shared hit=35286 read=1059 -> Bitmap Index Scan on customer_c_phone_idx_c_acctbal (cost=0.00..6578.88 rows=382528 width=0) (actual time=72.756..72.756 rows=382464 loops=1) Index Cond: (substr((c_phone)::text, 1, 2) = ANY ('{27,21,33,15,18,26,12}'::text[])) Buffers: shared hit=8 read=1059 -> HashAggregate (cost=637729.50..637729.55 rows=3 width=20) (actual time=9220.081..9220.084 rows=7 loops=1) Buffers: shared hit=324005 read=1598 -> Hash Anti Join (cost=594299.29..637283.27 rows=59498 width=20) (actual time=8813.802..9200.636 rows=63549 loops=1) Hash Cond: (public.customer.c_custkey = orders.o_custkey) Buffers: shared hit=324005 read=1598 -> Bitmap Heap Scan on customer (cost=2940.15..41901.34 rows=140312 width=24) (actual time=482.887..623.589 rows=190958 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{27,21,33,15,18,26,12}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=70480 read=1598 -> Bitmap Index Scan on customer_c_phone_idx (cost=0.00..2905.08 rows=140312 width=0) (actual time=475.696..475.696 rows=190958 loops=1) Index Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{27,21,33,15,18,26,12}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=35295 read=1598 -> Hash (cost=403671.84..403671.84 rows=15014984 width=4) (actual time=8323.072..8323.072 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.022..4104.330 rows=15015000 loops=1) Buffers: shared hit=253522 Total runtime: 9357.477 ms (30 rows) COMMIT; COMMIT