Search code examples
sqljoinleft-join

Isn't SQL A left join B, just A?


I was looking at a few graphs to understand the difference between the joins, and I came across this image:

enter image description here

Maybe the problem is in representing this with Venn Diagrams.

But looking at the first join, top left, isn't that just A?

What difference does B make?


Solution

  • No, since it's a join, it can produce cardinalities greater than 1 for the rows in A. That is, if there are multiple matching rows from B then a row in A will show up multiple times.

    Example:

    Table A:

    id name
    -- -------
     1 Alice
     2 Malcolm
     3 Kelly
    

    Table B:

    id_a preferred_food
    ---- --------------
       1 Pizza
       2 Burger
       2 Steak
       2 Minestroni
    

    Then "A left join B" will give you:

    id name    id_a preferred_food
    -- ------- ---- --------------
     1 Alice      1 Pizza
     2 Malcolm    2 Burger
     2 Malcolm    2 Steak
     2 Malcolm    2 Minestroni
     3 Kelly   null null
    

    In short:

    • All rows from A show up in the left join: even 3 Kelly shows up.
    • Columns from B will show up with nulls when there are no matching rows in B: row 3 Kelly has null in the last two columns.
    • Rows in A may show up multiple times when they have multiple matches in B: row 2 Malcolm shows up three times.