Explain the difference between a Nested Loop Join, a Hash Join, and a Merge Join. When would the query optimizer choose one over the others?

Last updated 3 July 2026

  • Nested Loop probes the inner table for each outer row. It is best when one side is small and the inner join key is indexed.

  • Hash Join builds a hash table on the smaller input and probes it with the larger one. It suits large, unsorted, unindexed equality joins only.

  • Merge Join zips together two inputs sorted on the join key, ideal when data is already sorted. The optimizer chooses based on statistics and cost estimates.

  • https://learn.microsoft.com/en-us/sql/relational-databases/performance/joins?view=sql-server-ver17
  • https://dev.to/philip_mcclarence_2ef9475/postgresql-join-optimization-nested-loop-hash-and-merge-1cn9
  • https://arpitbhayani.me/blogs/join-algorithms/
  • https://www.geeksforgeeks.org/dbms/nested-loop-join-in-dbms/
  • https://rafaelrampineli.medium.com/optimizing-sql-server-joins-understanding-nested-loops-hash-match-merge-join-and-adaptive-join-5ba57fcf6ec3
  • https://medium.com/@milhamsuryapratama/sql-join-algorithms-nested-loop-merge-and-hash-join-f264a34194e3
All SQL interview questions