LEFT JOIN vs RIGHT JOIN decision in SQL - Performance Comparison
When using LEFT JOIN or RIGHT JOIN in SQL, it's important to understand how the time to run the query grows as the data grows.
We want to know how the choice between LEFT JOIN and RIGHT JOIN affects the work the database does.
Analyze the time complexity of this SQL join query.
SELECT a.id, b.value
FROM tableA a
LEFT JOIN tableB b ON a.key = b.key;
This query returns all rows from tableA and matches rows from tableB where keys are equal.
Look at what repeats as the database processes the join.
- Primary operation: For each row in tableA, the database looks for matching rows in tableB.
- How many times: This happens once for every row in tableA.
As tableA grows, the number of lookups in tableB grows too.
| Input Size (rows in tableA) | Approx. Operations |
|---|---|
| 10 | About 10 lookups in tableB |
| 100 | About 100 lookups in tableB |
| 1000 | About 1000 lookups in tableB |
Pattern observation: The work grows roughly in direct proportion to the size of tableA.
Time Complexity: O(n)
This means the time to run the join grows linearly with the number of rows in the left table.
[X] Wrong: "LEFT JOIN is always slower than RIGHT JOIN because it processes more data."
[OK] Correct: The speed depends on which table is on the left or right and their sizes, not just the join type name.
Understanding how join direction affects query time helps you write efficient queries and explain your choices clearly in interviews.
What if we swapped the tables and used RIGHT JOIN instead? How would the time complexity change?