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 ('24', '28', '21', '12', '16', '17', '18') and c_acctbal > ( select avg(c_acctbal) from customer where c_acctbal > 0.00 and substr(c_phone, 1, 2) in ('24', '28', '21', '12', '16', '17', '18') ) and not exists ( select * from orders where o_custkey = c_custkey ) ) as vip group by cntrycode order by cntrycode; QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=693630.08..693630.09 rows=3 width=20) (actual time=15298.496..15298.496 rows=7 loops=1) Sort Key: (substr((public.customer.c_phone)::text, 1, 2)) Sort Method: quicksort Memory: 25kB Buffers: shared hit=316341 read=10512 InitPlan 1 (returns $0) -> Aggregate (cost=52950.00..52950.01 rows=1 width=4) (actual time=798.829..798.830 rows=1 loops=1) Buffers: shared hit=26368 read=9975 -> Bitmap Heap Scan on customer (cost=6674.46..51993.69 rows=382523 width=4) (actual time=179.300..702.165 rows=382123 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{24,28,21,12,16,17,18}'::text[])) AND (c_acctbal > 0::double precision)) Buffers: shared hit=26368 read=9975 -> Bitmap Index Scan on customer_c_phone_idx_c_acctbal (cost=0.00..6578.83 rows=382523 width=0) (actual time=161.869..161.869 rows=382123 loops=1) Index Cond: (substr((c_phone)::text, 1, 2) = ANY ('{24,28,21,12,16,17,18}'::text[])) Buffers: shared hit=9 read=1057 -> HashAggregate (cost=640680.01..640680.05 rows=3 width=20) (actual time=15298.413..15298.417 rows=7 loops=1) Buffers: shared hit=316339 read=10512 -> Hash Anti Join (cost=597249.92..640233.77 rows=59498 width=20) (actual time=14686.147..15272.085 rows=63404 loops=1) Hash Cond: (public.customer.c_custkey = orders.o_custkey) Buffers: shared hit=316339 read=10512 -> Bitmap Heap Scan on customer (cost=2940.08..41901.22 rows=140310 width=24) (actual time=892.410..1150.246 rows=190834 loops=1) Recheck Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{24,28,21,12,16,17,18}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=61549 read=10512 -> Bitmap Index Scan on customer_c_phone_idx (cost=0.00..2905.01 rows=140310 width=0) (actual time=881.023..881.023 rows=190834 loops=1) Index Cond: ((substr((c_phone)::text, 1, 2) = ANY ('{24,28,21,12,16,17,18}'::text[])) AND (c_acctbal > $0)) Buffers: shared hit=26378 read=10512 -> Hash (cost=405686.04..405686.04 rows=15089904 width=4) (actual time=13785.128..13785.128 rows=15015000 loops=1) Buckets: 2097152 Batches: 1 Memory Usage: 527872kB Buffers: shared hit=254787 -> Seq Scan on orders (cost=0.00..405686.04 rows=15089904 width=4) (actual time=0.021..5545.423 rows=15015000 loops=1) Buffers: shared hit=254787 Total runtime: 15442.463 ms (30 rows) COMMIT; COMMIT