What happens when there are multiple matching records in a join table?
20 August 2023 (Updated 27 April 2025)
Suppose you had the following tables:
users

articles

And you executed the following query:
SELECT a.id article_id, u.id user_id
FROM articles a
LEFT JOIN users u ON u.id = a.user_id
The result would look something like:

We get two records in the result set where the user_id
is 1
because of how the SQL engine handles multiple matching records in a join table:
- The SQL engine begins by selecting a row from the
articles
table (let’s call it “Row A”).
It then performs aLEFT JOIN
with theusers
table based on the conditionu.id = a.user_id
. - It searches the
users
table for a row where the value ofu.id
(users.id
) is equal to the value ofa.user_id
(articles.id
) from “Row A”. If multiple matches are found as is the case whena.user_id
is1
, then it generates a new row set in the result set. - The result set for “Row A” includes the
id
column from “Row A” and the correspondinguser_id
column from “Row U” (if a match was found) orNULL
(if no match was found).
Steps 1-3 are repeated for each row.
Tagged:
SQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment