Below two queries result the same result set. In first I have only used INNER JOIN
and in second query mix of joins like LEFT
and RIGHT JOIN
. I personally prefer INNER JOIN
when there is no specific task/requirement of other joins. But I just want to know that is there any difference between the below two queries in terms of performance or execution time. Is it ok to use inner join
than the mix of joins?
1.
SELECT film.title, category.name, film.rating, language.name
FROM film INNER JOIN film_category ON film_category.film_id = film.film_id
INNER JOIN category ON category.category_id = film_category.category_id
INNER JOIN language ON language.language_id = film.language_id
WHERE category.name = "Sci-Fi" AND film.rating = "NC-17";
SELECT film.title, film.release_year, film.rating,category.name, language.name
FROM film LEFT JOIN language ON language.language_id=film.language_id
RIGHT JOIN film_category ON film_category.film_id = film.film_id
LEFT JOIN category ON category.category_id=film_category.category_id
WHERE film.rating="NC-17" AND category.name="Sci-Fi";
2
Answers
Please see this INNER JOIN vs LEFT JOIN performance in SQL Server.
However, choosing the proper join type is depending on the usecase and result set which you need to extract.
Please do not mix the different types except in this way: INNER, INNER, … LEFT, LEFT, … Any other combination has ambiguities about what gets done first. If you must mix them up, use parentheses to indicate which JOIN must be done before the others.
As for whether INNER/LEFT/RIGHT are identical, let me explain with one example:
That WHERE effectively turns the
LEFT JOIN
intoINNER JOIN
. The Optimizer will do such. I, as a human, will stumble over the query until I realize that. So, humor me by calling itINNER JOIN
.Phrased another way, use
LEFT
only when the "right" table’s columns are optional, but you wantNULLs
when they are missing. Of course, you may want the NULLs so you can say "find rows ofa
that are not inb
:While I have your attention, here are some notes/rules:
INNER
,CROSS
, andOUTER
are ignored by MySQL. TheON
andWHERE
clauses will determine which type of JOIN is really intended.RIGHT JOIN
. Please convert it to aLEFT JOIN
.ON
to specify how the tables are related and useWHERE
for filtering. (With INNER, they are equivalent; with LEFT, you may get different results.)EXISTS( SELECT ... )
is better than aLEFT JOIN
.GROUP BY
,ORDER BY
, andLIMIT
. But that is a loooong discussion.Back to your question of which is faster, etc. Well, if the Optimizer is going to turn one into another, then those two have identical performance.