3
\$\begingroup\$

I have following queries

First one using inner join

SELECT item_ID,item_Code,item_Name 
FROM [Pharmacy].[tblitemHdr] I INNER JOIN  EMR.tblFavourites F ON I.item_ID=F.itemID
WHERE F.doctorID = @doctorId AND F.favType = 'I'

second one using sub query like

SELECT item_ID,item_Code,item_Name from [Pharmacy].[tblitemHdr]
WHERE item_ID IN
(SELECT itemID FROM EMR.tblFavourites
WHERE doctorID = @doctorId AND favType = 'I'
)

In this item table [Pharmacy].[tblitemHdr] Contains 15 columns and 2000 records. And [Pharmacy].[tblitemHdr] contains 5 columns and around 100 records. in this scenario which query gives me better performance?

\$\endgroup\$
1

2 Answers 2

3
\$\begingroup\$

The SQL Server query analyzer is smart enough to understand that these queries are identical (given that item_ID is unique in EMR.tblFavourites for a certain doctorID/favType pair).

They should yield exactly the same execution plan, and thus they are equal in terms of performance. I would prefer second variant though...

\$\endgroup\$
1
\$\begingroup\$

I'm not familiar with Microsoft SQL server (I assume that this is actual SQL server mentioned here). Actually I'm pretty sure that IN will not produce multiplication of rows if there is two entries for single F.itemID in contrast with INNER JOIN.

I suspect that with absence of unique index on F.itemID performance may differ too. Probably IN will prefer to ordered unique set of relations while FROM will consider statistics of both tables more equally than IN.

P.S. I prefer JOIN because of giving hint for optimizer while dropping off additional constraint. And it looks a bit more readable as for me (less amount of SELECT).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.