---
title: "SQL Server 2008: Why table scanning when another logical condition is satisfied first?"  
description: "SQL Server 2008: Why table scanning when another logical condition is satisfied first?"  
author: "Anonymous User"  
published: 2013-05-08  
updated: 2013-05-08  
canonical: https://www.mindstick.com/forum/838/sql-server-2008-why-table-scanning-when-another-logical-condition-is-satisfied-first  
category: "mssql server"  
tags: ["mssql server"]  
reading_time: 2 minutes  

---

# SQL Server 2008: Why table scanning when another logical condition is satisfied first?

Hi [Expert](https://www.mindstick.com/articles/13120/an-expert-financial-advice-will-improve-your-finances)!\
Consider following piece of code:\
declare @var bit = 0\
select * from tableA as Awhere1=(case when @var = 0 then 1 when exists(select null from tableB as B where A.id=B.id) then 1 else 0end)Since [variable](https://www.mindstick.com/articles/1807/objective-c-data-types-variables-object-creation) @var is set to 0, then the [result](https://www.mindstick.com/blog/12011/advantages-of-getting-result-oriented-seo-from-an-agency) of evaluating searched case [operator](https://www.mindstick.com/blog/144/union-intersection-and-except-operator-in-sql-server) is 1. In the [documentation](https://answers.mindstick.com/qa/30462/what-is-documentation) of case it is written that it is evaluated until \
first WHEN is TRUE. But when I look at [execution plan](https://www.mindstick.com/forum/160276/what-is-an-execution-plan-in-sql-server), I see that tableB is scanned as well.\
Does anybody know why this happens? Probably there are ways how one can avoid second table scan when another [logical](https://www.mindstick.com/forum/33581/what-is-inserted-deleted-logical-table-in-sql-server) [condition](https://www.mindstick.com/forum/12711/select-query-with-and-condition) is evaluated to TRUE?\
Thanks in [advance](https://www.mindstick.com/blog/33258/jee-mains-and-jee-advance-exams)!

## Replies

### Reply by AVADHESH PATEL

Hi Ankita!\
Because the plan that is compiled and cached needs to work for all possible values of @var\
You would need to use something like\
if (@var = 0)select * from tableA elseselect * from tableA as Awhere exists(select * from tableB as B where A.id=B.id) Even OPTION RECOMPILE doesn't look like it would help actually. It still doesn't give you the plan you would have got with a literal 0=0\
declare @var bit = 0\
select * from master.dbo.spt_values as Awhere1=(case when 0 = @var then 1 when exists(select null from master.dbo.spt_values as B where A.number=B.number) then 1 else 0end)option(recompile)


---

Original Source: https://www.mindstick.com/forum/838/sql-server-2008-why-table-scanning-when-another-logical-condition-is-satisfied-first

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
