Join vs. sub-query
Taken from the MySQL manual (13.2.10.11 Rewriting Subqueries as Joins):
A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.
So subqueries can be slower than LEFT [OUTER] JOIN
, but in my opinion their strength is slightly higher readability.
Understanding when to use a subquery over a join
Good Read for Subquery vs Inner Join
https://www.essentialsql.com/subquery-versus-inner-join/
Subqueries vs joins
A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically.
But, yeah, explain-plan will give you the dirty details.
SQL Joins Vs SQL Subqueries (Performance)?
I would EXPECT the first query to be quicker, mainly because you have an equivalence and an explicit JOIN. In my experience IN
is a very slow operator, since SQL normally evaluates it as a series of WHERE
clauses separated by "OR" (WHERE x=Y OR x=Z OR...
).
As with ALL THINGS SQL though, your mileage may vary. The speed will depend a lot on indexes (do you have indexes on both ID columns? That will help a lot...) among other things.
The only REAL way to tell with 100% certainty which is faster is to turn on performance tracking (IO Statistics is especially useful) and run them both. Make sure to clear your cache between runs!
Related Topics
How to Delete Duplicate Records in MySQL Database
Get Records With Max Value For Each Group of Grouped SQL Results
Entity Attribute Value Database Vs. Strict Relational Model Ecommerce
Get Top Results For Each Group (In Oracle)
MySQL Update Column With Value from Another Table
Calculate Age in MySQL (Innodb)
Rails 4 Like Query - Activerecord Adds Quotes
How to Escape a Single Quote in SQL Server
Best Approach to Remove Time Part of Datetime in SQL Server
How to Use Returning With on Conflict in Postgresql
MySQL - How to Unpivot Columns to Rows