# `MergeJoin` Operator

__*Probe也是在memory里的？*__

+ Build a sorted table in memory on the `build side`
+ Read the sorted data to probe the sorted table on the `probe side`

![`smart`](MergeJoin01_aa_001_20230913.png)

------------------------------------------------------------------------------
The `MergeJoin` operator in TiDB is optimized for situations where both sides of the join are sorted by the join keys. Here’s how it works:

`Build Side:`
- The build side is processed first and loaded into memory.
- All rows that form a complete Join Group from the build side (i.e., rows with the same values for all join keys) are read into memory.
- Operators such as `IndexFullScan` or `IndexRangeScan` are used to retrieve the data.
- Data on the build side must be sorted by the join keys to ensure efficient merging.

`Probe Side:`
- Once the build side data is loaded, the probe side data is processed.
- Each row from the probe side is compared against the Join Groups from the build side stored in memory.
- The probe side data is also read in sorted order, facilitating efficient comparison with the build side.
- The `TableRowIDScan` operator is commonly used to retrieve row data based on the `RowID` obtained from an index scan.

This method leverages sorted data to perform the join operation efficiently by comparing sorted rows from both sides.