I have a query that searches a large table with around 1mln discount records and i'm having an index problem with this table.
SELECT TOP 1 D.Discount
FROM Discount D
WHERE (D.ProductGroupId = @ProductGroupId OR D.ProductId = @ProductId)
AND (D.CampaignId IS NULL AND (D.CustomerGroupId = @CustomerGroupId OR D.CustomerId = @CustomerId OR (D.CustomerId IS NULL AND D.CustomerGroupId IS NULL)))
AND getDate() BETWEEN D.StartDate AND D.EndDate
AND D.Quantity = 1
ORDER BY D.Discount DESC
The where clauses on the product / productgroup, the startdate / enddate and quantity all work well. Without any special indexes on this table, i'll find the correct discount in about 2 seconds. (which is not that fast, but nowhere near dramatic in this case).
The problem is with the campaignId/CustomerGroupId/CustomerId part. Adding this part makes the query to run for over 2 minutes. I'm sure this can be solved, perhaps using a correct index, but i have been trying to setup all kinds of indexes, but nothing worked.
ORclauses aren't going to help performance. What is the actual usage of this? Do you only pass in one of@ProductGroupId/@ProductIdand one of@CustomerGroupId/@CustomerId?