Is there a faster way to write the following query on a table called OrderDtl?
OrderId Product
1 ORANGE
1 APPLE
2 SHAMPOO
2 SOAP
2 TOOTHPASTE
SELECT *
FROM OrderDtl
WHERE OrderId in
(
SELECT OrderId
FROM OrderDtl
WHERE Product='APPLE'
)
Which results in
1 ORANGE
1 APPLE
Join the table to itself.
After seeing the comment from Dems I changed the SQL to add a couple of indexes:
Comparing the resulting execution plans is interesting, for this trivial example the result is the same:
EDIT:
Adding the execution plan of esastincy answer, it’s the same again in execution “effort”
You may also be interested in this article: SQL Server: JOIN vs IN vs EXISTS – the logical difference