Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 300
porton Avatar asked Mar 13 '23 10:03

porton


1 Answers

"Is there any reason why this code was written with a subquery"

a very long time ago MySQL joins used to be slow

like image 101
Emil Perhinschi Avatar answered Mar 15 '23 09:03

Emil Perhinschi