Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. Row count after joining on duplicate keys

SQL · Tricky Output & Semantics

Row count after joining on duplicate keys

Easysql-43
joinsduplicatesfan-outrow-count

Question

Table A has 3 rows with key 1, table B has 4 rows with key 1. How many rows does A INNER JOIN B return, and what about LEFT JOIN when B has no match?

Solution

A.key = 1 appears 3 times and B.key = 1 appears 4 times. An inner join pairs every A row with every B row that has the same key, so you get 3 x 4 = 12 rows.

Why the join multiplies

A join does not match "one to one". For each key value it builds all the pairs. With 3 rows on one side and 4 on the other, that is 12 pairs. If the key had 1 row on each side you would get 1.

A (key)   B (key)      INNER JOIN on key
  1         1            A1-B1, A1-B2, A1-B3, A1-B4
  1         1            A2-B1, A2-B2, A2-B3, A2-B4
  1         1            A3-B1, A3-B2, A3-B3, A3-B4
            1            = 12 rows

LEFT JOIN when B has no match

If an A row has a key that is not in B, a LEFT JOIN still returns it once, with NULLs in all B columns. So unmatched rows do not multiply. Matched rows still multiply exactly as in the inner join.

One more detail: NULL keys never match, not even another NULL. NULL = NULL is UNKNOWN. A row with a NULL key falls out of an inner join and shows up with NULLs from the other side in a left join.

The bug this causes in real work

Say orders has one row per order and you join it to customer_addresses, which has two rows for a customer who moved. Every order of that customer now appears twice, and SUM(order_total) is doubled. Nobody sees an error. The dashboard is just wrong.

Before joining, check that the key is unique on the side you expect to be "one":

SELECT customer_id, COUNT(*)
FROM customer_addresses
GROUP BY customer_id
HAVING COUNT(*) > 1;

A fast sanity check after any join: compare the row count with the base table. If it went up and you did not mean to fan out, the join key is not unique.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext