The Optimizer is the "brain" brain of the database, interpreting SQL queries and choose the fastest execution method. In this tutorial I will use explain command to show how the optimizer interprets and execute query.
1. What decisions does the optimizer have to make
Scan method
Join method
Join Order
2. Which scan method ?
Sequential Scan
Bitmap Index Scan
Index Scan
2.2 Sequential Scan
2.3 Index Scan
2.4 Bitmap Index Scan
2.5 Demo
How we force to use Index Scan only ???
Conclusion : Optimizer refer the lower cost
3. Which JOIN method ?
Nested Loop
With Inner Sequential Scan
With Inner Index Scan
Hash Join
Merge Join
3.1 Nested Loop
These tables have no indexes and no optimizer statistics
Pseudocode
3.2 Hash Join
Join the Two Tables with a Looser Restriction
Pseudocode
3.3 Merge Join
Pseudocode
Query Restrictions Affect Join Usage
All ’junk’ Columns Begin with ’xxx’
Hash join was chosen because many more rows are expected. The smaller table, e.g., sample2, is always hashed.
LIMIT
Without LIMIT, Hash Is Used for this Unrestricted Join
LIMIT Can Affect Join Usage
Sort is unneeded since an index is being used on the outer side.
LIMIT 100 Switches to Merge Join
Merge join is normally used for large joins, but the indexes eliminate the need for sorting both sides band LIMIT reduces the number of index entries that need to be accessed.
LIMIT 1000 Switches Back to Hash Join
VACUUM Causes Merge Join Again
VACUUM reduces the cost of the index-only scan by making heap access less likely, so merge join again becomes the cheapest option. The inner index scan has also changed to
No LIMIT Was a Merge Join
Same Join, Different Plans
|Query Modifier| Plan|
| ----------- | ----------- |
|No LIMIT| Hash Join|
|LIMIT 1| Nested loop join with two index scans|
|LIMIT 10| Nested loop join with two index scans|
|LIMIT 100| Merge join with two index scans|
|LIMIT 1000| Hash join|
|VACUUM, LIMIT 1000| Merge join with index scan and sort|
|No LIMIT| Merge join with index scan and sort|
The last two are different from previous matching lines because of VACUUM.