Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does LEFT JOIN return same row count as left table?

Tags:

sql

SELECT * 
FROM t1
LEFT JOIN t2 ON t1.fk = t2.id;

Will it always return the same row count as that of t1 ?

like image 470
Ludovic Aubert Avatar asked Feb 17 '26 04:02

Ludovic Aubert


1 Answers

The contract of a left join states that, in the absence of a WHERE clause which might remove records from the result set, all records which appear in the left side of the join will appear at least once. Consider the following data set:

t1
id | fk
1  | 1
2  | 2

t2
id | value
1  | 1
1  | 2

Your query would return this result set:

id | fk | id   | value
1  | 1  | 1    | 1
1  | 1  | 1    | 2
2  | 2  | NULL | NULL

Note carefully that the first table's fk = 2 did not match anything to the second table. This record still appears in the result set, but all columns coming from the second table are NULL. Also, note that fk = 1 records appear twice, because that single record in the first table matched twice to the second table.

like image 157
Tim Biegeleisen Avatar answered Feb 18 '26 16:02

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!