Skip to content

Commit ee49b8d

Browse files
committed
tuning joins
1 parent 543c5c5 commit ee49b8d

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/***************** Tuning Joins *******************/
2+
3+
--------------- Nested Loop --------------------------------------------------
4+
5+
-- force query plan builder to use nested loop first, just for testing purpose
6+
set enable_nestloop = true;
7+
set enable_hashjoin = false;
8+
set enable_mergejoin = false;
9+
10+
EXPLAIN SELECT s.id,s.last_name,s.job_title,cr.country
11+
FROM staff s
12+
JOIN company_regions cr
13+
ON cr.region_id = s.region_id;
14+
15+
16+
/*
17+
We can see that builder use Nested Lop then Index Scan using primary key (region_id).
18+
As postgreSQL automatically created index on primary key, we will delete this key (for testing purpose)
19+
and see how Nest Loop will full table scan will look like in performance wise.
20+
*/
21+
22+
23+
EXPLAIN SELECT s.id,s.last_name,s.job_title,cr.country
24+
FROM staff s
25+
JOIN company_regions cr
26+
ON cr.region_id = s.region_id;
27+
28+
/* we can see that Cost got increased.
29+
30+
So main take away is when we are using any kind of joins (especially, Nested Loop), it helps to ensure foreign keys
31+
columns and the columns you are trying to matching on are indexed properly.
32+
*/
33+
34+
35+
--------------- Hash Join --------------------------------------------------
36+
set enable_nestloop = false;
37+
set enable_hashjoin = true;
38+
set enable_mergejoin = false;
39+
40+
41+
EXPLAIN SELECT s.id,s.last_name,s.job_title,cr.country
42+
FROM staff s
43+
JOIN company_regions cr
44+
ON cr.region_id = s.region_id;
45+
46+
/*
47+
We can see that in row 3, scanning on staff table.
48+
in row 4, hash table is being buit.
49+
*/
50+
51+
--------------- Merge Join --------------------------------------------------
52+
53+
set enable_nestloop = false;
54+
set enable_hashjoin = false;
55+
set enable_mergejoin = true;
56+
57+
58+
EXPLAIN SELECT s.id,s.last_name,s.job_title,cr.country
59+
FROM staff s
60+
JOIN company_regions cr
61+
ON cr.region_id = s.region_id;
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+
76+
77+

0 commit comments

Comments
 (0)