Code
Code

Reputation: 6251

LEFT JOIN or INNER JOIN?

I have the following tables. All fields are NOT NULL.

tb_post
    id
    account_id
    created_at
    content

tb_account
    id
    name

I want to select the latest post along with the name. Should I use INNER JOIN or LEFT JOIN? From my understanding both produce the same results. But which is more correct or faster?

SELECT p.content, a.name
FROM tb_post AS p
[INNER or LEFT] JOIN tb_account AS a
ON a.id = p.account_id
ORDER BY p.created_at DESC
LIMIT 50

Upvotes: 0

Views: 81

Answers (4)

Herbert Van-Vliet
Herbert Van-Vliet

Reputation: 754

I personally don't think speed is very relevant: the difference between them is what they do.

They happen to give the same result in your case, but that does not mean they can be interchanged, because choosing the one or the other still tells the other guy that reads your code something.

I tend to think like this: INNER JOIN - the two tables are basically ONE set, we just need to combine two sources. LEFT JOIN - the left tables is the source, and optionally we may have additional information (in the right table).

So if I would read your code and see a LEFT JOIN, that's the impression you give me about your data model.

Upvotes: 0

Niels B.
Niels B.

Reputation: 6310

You have to ask yourself two questions.

1) Is there any chance that at some point in your application lifetime, there will be posts with an empty or invalid account_id?

If not, it doesn't matter.

If yes...

2) Would it be desirable to include posts without an associated account in the result of the query? If yes, use LEFT JOIN, if no, use INNER JOIN.

Upvotes: 0

user5621153
user5621153

Reputation:

A LEFT JOIN is absolutely not faster than an INNER JOIN. In fact, it's slower; by definition, an outer join (LEFT JOIN or RIGHT JOIN) has to do all the work of an INNER JOIN plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.

(And even if a LEFT JOIN were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN, so you cannot simply go replacing all instances of one with the other!)

Better go for INNER JOIN.

Upvotes: 1

Abhishek
Abhishek

Reputation: 3398

As Per My View The Correct One Is Inner join

because it returns resultset that include only matched elements where Left Join Returns all entries from Left Table. In this case I think Inner join returns the only required amount of data to be proceed.

Upvotes: 0

Related Questions