porton porton - 7 months ago 14
SQL Question

Weird SQL code: Why do they use a subquery instead of join?

I met the following MySQL code:

SELECT ServiceFee
FROM Shows
WHERE ID = (SELECT ShowID FROM Orders WHERE ID = ?)


It makes me wonder because the people who wrote this code usually use SQL joins. I would rewrite it

SELECT ServiceFee
FROM Shows
INNER JOIN Orders ON Shows.ID = Orders.ShowID
WHERE Orders.ID = ?


My question: Is there any reason why this code was written with a subquery and whether it is completely safe (producing the same result in all situations) to rewrite it with the join?

Are there any caveats?

Answer

Nope, there are no caveats. As a matter of fact, the INNER JOIN query might run faster