JOINS
- aka
INNER JOIN
ON
is likeWHERE
, but it applies specifically to joins
It’s always correct to think about basic JOIN
s as two nested loops with a filter, like this:
-
For each person in the people table:
- For each cat in the cats table:
- If the
ON
condition is true for this person and this cat:- Return a row with the columns from this person and this cat.
- If the
- For each cat in the cats table:
-
It’s common for tables to have the same column names, especially for
id
columns. This can get very confusing, so it’s best to useAS
to explicitly alias every joined column, rather than blindly selecting*
. That will make your SQL code more clear to other programmers.
Performance
- Nested loops are a perfect mental model for how
JOIN
works, but they’re only a mental model. In reality, the database will optimize the query, rebuilding it to be more efficient while still giving the same results.