5

What is better in a WHERE clause?

I have a large table, with a FK to a small table. I can search on the FK directly, or I can join to the FK table and set the WHERE restriction on the joined table. What is better / preferable?

So this:

SELECT lt.* FROM LargeTable lt 
WHERE lt.SomeId in(12,55)

Or this:

SELECT lt.* FROM LargeTable lt 
INNER JOIN SmallTable st ON lt.SomeId=st.ItemId
WHERE st.Id in(12,55)


I tested this with Set statistics time on, but I didn't expect this as a result. Who can explain what happens here?

First test without join:

(946 row(s) affected)
 SQL Server Execution Times:
   CPU time = 1544 ms,  elapsed time = 1580 ms.

Second test with the join

(946 row(s) affected)
 SQL Server Execution Times:
   CPU time = 2636 ms,  elapsed time = 366 ms.

EDIT: When i do SELECT Id instead of SELECT *, then the first query without join has a lower elapsed time, and the query cost in the execution plan is 25% for no join vs 75% for the query with the join.

8
  • 2
    You should include the actual execution plan, and then run both queries side by side... SQL Server will tell you which one is faster, and why it is faster. Dec 21, 2011 at 16:13
  • +1 for Actual Execution Plan. No need to guess. Dec 21, 2011 at 16:21
  • @RedFilter: Nope, but I can include an index if its necessary. Dec 21, 2011 at 16:24
  • @MichaelFredrickson: The execution plans are really simple. Without join is just a clustered index scan (100%). With join is also a clustered index scan (98%) and a clustered index seek on the small table, going together in a Hash Match. Query cost relative to batch is 50% for both. Dec 21, 2011 at 16:24
  • 6
    Your second one gets a parallel plan the first one doesn't. Dec 21, 2011 at 16:29

3 Answers 3

4

Based on your execution plans, both queries are essentially scanning every record in the entire large table... the second query is simply finding a small set of records from the small table before scanning the large table, which is why the relative cost is 50% for both.

I'd recommend considering an index on largeTable.SomeId, and then go with the first query:

SELECT lt.* FROM LargeTable lt 
WHERE lt.SomeId in(12,55)

EDIT:

So the big question is why did the query with the join have a shorter duration than the query without the join.

I think Martin Smith gave the answer to this question:

Your second one gets a parallel plan the first one doesn't

You'll notice that your first query had a shorter CPU time, but a longer elapsed time. To roughly summarize, your first query took less effort for the server to complete, but your second query used a parallel plan, and enlisted multiple processors to perform the query, so it took less time to complete, but more overall effort.

4
  • 1
    Agreed - If you already know the ids, and don't need the information (or restrict the rows somewhow) why do the join? Of course, if you've only got the ids because you pulled them out somewhow earlier (like a SELECT id WHERE key = @input), you may want to refactor that... Dec 21, 2011 at 17:13
  • @X-Zero: That was my first thought, but then I got those unexpected times, so I wondered what would be better / faster. I'm going to add an index and forget about the join, but I was just wondering why. Dec 21, 2011 at 17:29
  • @ErikDekker - This should be considered for more than a performance perspective (which can change unexpectedly, for apparently 'unrelated' reasons); if you're joining to a table, I would expect it to be important to the context for some reason - that you're attempting to restrict (or multiply) the results in some fashion, or retrieve some data. If neither of those is obviously being done, it can create worrisome confusion that something was missed. Dec 21, 2011 at 17:42
  • Credits to Martin Smith for the parallel. That was it! Credits to you for looking at my actual question. Dec 22, 2011 at 9:25
0

2 things to consider:

  1. did your inner join return a smaller set of data? in this case your where condition is executed on less rows.
  2. I think in your second query you meant to say where st.Id in (12, 55), in which case, your where clause is running against a primary key index which is clustered and hence alot faster than your non-clustered foreign key index
4
  • 1: both give me 946 rows (see Question). 2: Yes I meant that, I modified the question! (my tests were good tho) Dec 21, 2011 at 16:26
  • at the end both give you 946, but before you get to the where clause did your result set shrink? this would happen if your lt.SomeId is nullable, in which case all the record with no lt.SomeId are not evaluated by the where clause. if it's not nullable, then the only thing left is the second point (searching against the primary key is faster than searching against the foreign key, even after adding in the cost of the join Dec 21, 2011 at 16:31
  • But would they alawys give the same results? Is it possible to havea record in table1 with id 12 that is not also in table2? These two queries are functionally different. Inthe second query the data must exist in both tables in teh first query only in one table.
    – HLGEM
    Dec 21, 2011 at 17:30
  • @HLGEM the column in the where clause is a foreign key, so a record must exists in the second table, so both queries are essentially the same Dec 21, 2011 at 17:35
0
  1. As both queries are extracting results from large table as mentioned. So, Do you have Non clustered Index for the "SomeID" Column?

  2. Are you using all columns from this table. If this is not the case. It's recommended to mentioned required columns only.

  3. As both the queries are fetching data from large table so it can be done from first query only with "Non Clustered Index"

  4. If there is any case to get matched data only. Then you can do like below as well.

    Select ColumnName From
    (
     Select ColumnName, SomeID from LargeTable Where SomeID in(12,13)
    )T
    Inner Join SmallTable T1 on T.SomeID = T1.SomeID
    
  5. If you want very quick results. You can do like below.

    Create table #Large
    (
      Id Int,
      ColumnName Varchar(100)
    )
    Insert into #Large(ID, ColumnNmae)
    Select ColumnName, SomeID from LargeTable Where SomeID in(12,13)
    

And finally with join

Select ColumnName From #Large T
Inner Join SmallTable T1 on T.SomeID = T1.SomeID

and without Join

Select ColumnName from #Large

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.