tags:

views:

68

answers:

2

I have a query like this:

SELECT * 
FROM T
WHERE A = @A AND (B=@B OR C=@C OR D=@D OR @E=E)
ORDER BY F

What indices should I add to improve query performance? Also I'll need to implement paging so this query will be more complex.

My guess is that four indices should be created: (A, B, F), (A, C, F), (A, D, F) (A, E, F), but I'm not sure and can't really test it as I don't have enough data yet.

Does anyone have some experience to share? Thanks.

+3  A: 

Indices generally don't help you with this sort of OR logic Not knowing how much data you are getting or the complexity of the objects I can only speak subjectively but its often quicker to use union queries to sort the data down.

SELECT * from T
WHERE a= @a  and B= @b
UNION  
SELECT * from T
WHERE a= @a  and c= @c
UNION
SELECT * from T
WHERE a= @a  and d= @d
union
SELECT * from T
WHERE a= @a  and e= @e
u07ch
just wanted to tell the same thing
be here now
note that UNION removes duplicates, so your approach may be slow
AlexKuznetsov
Its a valid point; this replicates the functionality of the original query with more discreet indices than the or approach. In my experience on high data churn databases the union approach is more efficient than large covering indices as the cost of the index on row creation and deletion is too high.
u07ch
Thanks. Just one more thing, if separate indices exist, would SQL Server know how to use them in 'OR' query or I have to use 'UNION' query?
Marko
+1  A: 

A covering index should do.

created nonclustered index ([IDX_Cover])
on dbo.Table (columns to select)
include (columns in where clause)

remember, select * is not easily indexable. instead, index for what you need.

DForck42