473,416 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

Rewrite a WHERE clause

I have a WHERE clause that could be an "=" or a "LIKE" depending upon
if the passed variable is populated or not. I would like to know the
best way to write the WHERE clause to make it dynamically switch
between the 2 and make best use of the indexes.

CREATE TABLE myTable(ID INT PRIMARY KEY CLUSTERED, COUNTY VARCHAR(50))
CREATE INDEX IDX_myTable_County ON myTable(COUNTY)

DECLARE @COUNTY VARCHAR(50)
SET @COUNTY = 'SANTA CLARA' -- Could also be SET @COUNTY = NULL

SELECT ID FROM myTable
WHERE COUNTY LIKE (CASE WHEN @COUNTY IS NOT NULL THEN @COUNTY ELSE '%'
END)

This does not seem like best practice to me because I am forced to use
"LIKE" even when @COUNTY is populated with data. Ultimately I'd like:

WHERE (CASE WHEN @COUNTY IS NOT NULL COUNTY = @COUNTY ELSE COUNTY LIKE
'%' END)

but that is incorrect syntax on "=".

Also, I do not want to use a dynamically built statement. Is there a
way around this?

Thanks,
Josh

Aug 29 '05 #1
14 3241
Hello, Josh

See this article by Erland Sommarskog, SQL Server MVP:
http://www.sommarskog.se/dyn-search.html#Umachandar
There are some solutions in the article that are not using Dynamic SQL.

Razvan

Aug 29 '05 #2
Josh,

You might try this, if your data is all typical alphabetic
values in English (no letters of the alphabet that come
after Z). I'm also assuming your collation is case-insensitive.

where COUNTY >= coalesce(@COUNTY,'A')
and COUNTY <= coalesce(@COUNTY,'ZZZZZZZZZZZZZZZZZZZ')
-- as many Z's as the declared length of the COUNTY column

This may be more efficient than your LIKE solution, but the
only way to be certain is to do some comparisons. You also
run the risk in situations like this of getting bad cached
query plans, at least if your actual query selects more than
the ID column, since the best query plan for @COUNTY = NULL
is a table scan and the best query plan for @COUNTY <> NULL
is a non-clustered index seek followed by a bookmark lookup.
If the second plan is cached and used later when @COUNTY is
NULL, it will be very inefficient. A way around this, should
it occur, may be to add something to force query recompilation.
In a stored procedure, that might be adding WITH RECOMPILE,
or in an sp or otherwise, adding something to the query that
will prevent autoparameterization (adding AND 1 = 1 to the
WHERE clause will do this, I believe)

Maybe that's more than you needed to know, but your question
suggests you are thinking about some important considerations
in query design.

Steve Kass
Drew University

joshsackett wrote:
I have a WHERE clause that could be an "=" or a "LIKE" depending upon
if the passed variable is populated or not. I would like to know the
best way to write the WHERE clause to make it dynamically switch
between the 2 and make best use of the indexes.

CREATE TABLE myTable(ID INT PRIMARY KEY CLUSTERED, COUNTY VARCHAR(50))
CREATE INDEX IDX_myTable_County ON myTable(COUNTY)

DECLARE @COUNTY VARCHAR(50)
SET @COUNTY = 'SANTA CLARA' -- Could also be SET @COUNTY = NULL

SELECT ID FROM myTable
WHERE COUNTY LIKE (CASE WHEN @COUNTY IS NOT NULL THEN @COUNTY ELSE '%'
END)

This does not seem like best practice to me because I am forced to use
"LIKE" even when @COUNTY is populated with data. Ultimately I'd like:

WHERE (CASE WHEN @COUNTY IS NOT NULL COUNTY = @COUNTY ELSE COUNTY LIKE
'%' END)

but that is incorrect syntax on "=".

Also, I do not want to use a dynamically built statement. Is there a
way around this?

Thanks,
Josh

Aug 29 '05 #3
Thanks to both of you for your suggestions. I will try your methods and
see which is actually faster and which grabs the correct query plan
every time.

Aug 29 '05 #4
SQL programmers tend to trust the optimizer rather than write programs
that change on the fly. We also like the easiest to read form of
identical expressions:

county LIKE COALESCE (@my_county, '%')

Go with this and let the compiler figure out if the parameter is a
NULL, a string or a pattern. The LIKE predicate generates a simple
finite state machine to parse a string using the pattern given. The
state machine for '%' is very fast.

Aug 29 '05 #5
AK
I would keep things simple

if @COUNTY is NULL
--------- scan the table
select * from some_table
else
-------- might use an index
select * from some_table where conty = @county
end if

this way you'll have 2 precompiled plans for 2 different cases

Aug 29 '05 #6
--CELKO-- (jc*******@earthlink.net) writes:
SQL programmers tend to trust the optimizer rather than write programs
that change on the fly. We also like the easiest to read form of
identical expressions:

county LIKE COALESCE (@my_county, '%')

Go with this and let the compiler figure out if the parameter is a
NULL, a string or a pattern. The LIKE predicate generates a simple
finite state machine to parse a string using the pattern given. The
state machine for '%' is very fast.


On SQL 2000 this is a very poor advice. The query will table scan in
all cases. It should scan if @my_count is NULL of course. The optimizer
does not know when it builds the plan which value @my_county will have,
so it must have a plan that handles any value.

In SQL 2005 you can add the query hint

OPTION (RECOMPILE)

to get statement recompilation of that query only. In this case, it
will pick the plan which matches the value of @my_county best - or at
least I expect it two.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Aug 29 '05 #7
just add "= 1" to the end

here is a working example:
where (case when @arg is null then
case when
[property_id] = 1 //put your test when @arg is null here
then 1 else 0 end
else
case when
[property_id] = 2 //and your other one here
then 1 else 0 end
end) = 1

Aug 30 '05 #8
to explain

we are using case when <boolean> then 1 else 0 end

to get around sql servers strict handling of boolean type

then converting back from 1 > true and 0 > false at the end

you can't directly use "where case (blah)" because case doesn't return
a boolean value
but you can use "where case (blah) = 1" to convert the value coming out
of case to a boolean value

Aug 30 '05 #9
I thought that 2005 was geting a "multi-plan" feature like DB2. It
actually saves multiple exection plans and effectively does what AK
proposed, but without you having to tell it. Do you know if the OPTION
(RECOMPILE) discards or saves prior plans?

Aug 30 '05 #10
Morgan:
I don't understand quite what you mean. Can you use my query above and
fit it to your example?

Thanks,
josh

Aug 30 '05 #11
--CELKO-- (jc*******@earthlink.net) writes:
I thought that 2005 was geting a "multi-plan" feature like DB2.
That does not sound familiar. (Actually, already SQL 2000 have multiple
plans for a query, but this is related to the setting of SET options.)
It actually saves multiple exection plans and effectively does what AK
proposed, but without you having to tell it. Do you know if the OPTION
(RECOMPILE) discards or saves prior plans?


Since the hint instructs SQL Server to recompile the query each time, it
would be pointless to save the plan. (Compare stored procedure saved
WITH RECOMPILE; the plans for these are never in cache.)

OPTION (RECOMPILE) should be great for these dynamic search queries
where the user specifies the last name on one search and the next time
the shoe size.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Aug 30 '05 #12
joshsackett (jo*********@gmail.com) writes:
Morgan:
I don't understand quite what you mean. Can you use my query above and
fit it to your example?


What he said is that:

WHERE (CASE WHEN @COUNTY IS NOT NULL COUNTY = @COUNTY ELSE COUNTY LIKE
'%' END)

does not work, because you have mixed the CASE expression with the WHERE
condition. You could say:

WHERE COUNTY = CASE WHEN @COUNTy IS NOT NULL THEN @COUNTY ELSE COUNTY END

or briefer:

WHERE COUNTY = coalesce(@COUNTY, COUNTY)

(coalesce is just syntactic sugar for CASE WHEN x IS NOT NULL THEN x WHEN
....)

Or, as said earlier in the thread you could go for some elaborate trick for
dynamic searches.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Aug 30 '05 #13
"--CELKO--" <jc*******@earthlink.net> writes:
I thought that 2005 was geting a "multi-plan" feature like DB2. It
actually saves multiple exection plans and effectively does what AK
proposed, but without you having to tell it. Do you know if the OPTION
(RECOMPILE) discards or saves prior plans?


I think I've found what you are thinking of. You can store a "plan guide"
for a query. But this is fairly limited, as all you can do is to specify
an OPTION clause for the query. So for instance, you cannot force an
index this way.

You can play with parameters, so maybe you can get differnt plans for
different parameters, although I did not study it that deep.

It seems to me that the main use for this is when you have queries in a
third-party app that you cannot change, but which perfoms poorly.

--
Erland Sommarskog, Stockholm, es****@sommarskog.se

Sep 1 '05 #14
Erland Sommarskog (es****@sommarskog.se) writes:
"--CELKO--" <jc*******@earthlink.net> writes:
I thought that 2005 was geting a "multi-plan" feature like DB2. It
actually saves multiple exection plans and effectively does what AK
proposed, but without you having to tell it. Do you know if the OPTION
(RECOMPILE) discards or saves prior plans?


I think I've found what you are thinking of. You can store a "plan guide"
for a query. But this is fairly limited, as all you can do is to specify
an OPTION clause for the query. So for instance, you cannot force an
index this way.

You can play with parameters, so maybe you can get differnt plans for
different parameters, although I did not study it that deep.

It seems to me that the main use for this is when you have queries in a
third-party app that you cannot change, but which perfoms poorly.


Oops! There was even more to it!

There is a new query hint USE PLAN. With this hint you can specify the
entire query plan. And since you specify USE PLAN in the OPTION clause,
it follows from this that you can indeed store an entire query plan
for a query. Since there is some parameterisation stuff with plan
guides as well, you might also be able to save more than one plan. I
have not dug into that yet.

--
Erland Sommarskog, Stockholm, es****@sommarskog.se

Sep 2 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: A.V.C. | last post by:
Hello, I found members of this group very helpful for my last queries. Have one problem with CASE. I can use the column name alias in Order By Clause but unable to use it in WHERE CLAUSE. PLS...
3
by: kalamantina | last post by:
How to rewrite this snippet if you must implement IDisposable private static void OpenConnection() { string connectionString = GetConnectionString(); StringBuilder errorMessages = new...
14
by: Stan Canepa | last post by:
This post is mostly for discussion. Why rewrite in .NET? Just a general discussion not related to any specific details. I was just looking to see what reasons developers are looking to, to help...
2
by: Jim.Mueksch | last post by:
I am having a problem with using calculated values in a WHERE clause. My query is below. DB2 gives me this error message: Error: SQL0206N "APPRAISAL_LESS_PRICE" is not valid in the context where...
9
by: Emin | last post by:
Dear Experts, I have a fairly simple query in which adding a where clause slows things down by at least a factor of 100. The following is the slow version of the query ...
8
by: chrisdavis | last post by:
I'm trying to filter by query or put those values in a distinct query in a where clause in some sort of list that it goes through but NOT at the same time. Example: ROW1 ROW2 ROW3 ROW4 ,...
5
by: pwiegers | last post by:
Hi, I'm trying to use the result of a conditional statement in a where clause, but i'm getting 1)nowhere 2) desperate :-) The query is simple: -------- SELECT idUser,...
4
by: Jane T | last post by:
I appreciate how difficult it is to resolve a problem without all the information but maybe someone has come across a similar problem. I have an 'extract' table which has 1853 rows when I ask for...
3
by: VGD | last post by:
"Serge Rielau" <srielau@ca.ibm.comescribió en el mensaje news:6e8m5mF5uf8oU1@mid.individual.net... Hello Serge I've checked that DB2 OS/390 8.1.5 accepts WITH clause but doesn't accept...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.