Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Instead of OR in WHERE clause
Message
From
04/02/2014 01:23:28
Walter Meester
HoogkarspelNetherlands
 
 
To
03/02/2014 23:00:12
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2008
Application:
Web
Miscellaneous
Thread ID:
01593065
Message ID:
01593093
Views:
29
>>This query
>>
>>select * from myTable where Condition1 OR Condition2
>>
>>is the same as
>>
>>select * from myTable where Condition1
>>UNION
>>select * from myTable where Condition2
>
>Is it really faster?

It very well could be. Complex where clauses with OR will take different execution plans. If you split up the statement with UNION and the where clause becomes more simple, the optimizer might choose a far more efficient execution plan.

We had an example of a frequently executed query that went don't from taking 5 seconds to 0.005 seconds, by using this strategy.

>Also, we need to consider that the select line is very big. So, if I have 1000 primary keys, I would have to repeat that line 1000 times.

You mean with the IN() clause. Ussually what I do is to put all the keys in a temp table and perform a join with it. Its possible to convert a comma delimited list passed as a parameter into a temp table. Eg
CREATE FUNCTION [dbo].[udf_List2Table]
(
@List VARCHAR(8000),
@Delim CHAR
)
RETURNS
@ParsedList TABLE
(
--*[2013/01/16 20:55:53] ndragan -  replaced SQL_Latin1_General_CP1_CI_AS with database_default
item VARCHAR(8000) COLLATE database_default,
ListOrder Int 
)
AS
BEGIN
DECLARE @item VARCHAR(8000), @Pos INT, @nT INT
SET @List = LTRIM(RTRIM(@List))+ @Delim
SET @Pos = CHARINDEX(@Delim, @List, 1)
SET @nT = 1
WHILE @Pos > 0
BEGIN
	SET @item = LTRIM(RTRIM(LEFT(@List, @Pos - 1)))
	IF @item <> ''
	BEGIN
		INSERT INTO @ParsedList (item, Listorder) VALUES (CAST(@item AS VARCHAR(8000)), @nT)
		SET @nT = @nT+1
	END
	SET @List = RIGHT(@List, LEN(@List) - @Pos)
	SET @Pos = CHARINDEX(@Delim, @List, 1)
END
RETURN
END
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform