Merge joins

Finally, there is a merge join. The idea here is to use sorted lists to join the results. If both sides of the join are sorted, the system can just take rows from the top and see if they match and return them. The main requirement here is that the lists are sorted. Here is a sample plan:

← Merge join    ← Sort table 1          ← Sequential scan table 1    ← Sort table 2          ← Sequential scan table 2 

To join, data has to be provided in sorted order. In many cases, PostgreSQL will just sort the data. However, there are other options to provide the join with sorted data. One way is to consult an index, as shown in the next example:

Merge joinSort table 1Sequential scan table 1Sort table 2Sequential scan table 2

One side of the join ...

Get Mastering PostgreSQL 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.