Which indexes do i need to create on an sql table in order for a certain query to run fast in al cases?

I have the following query:

SELECT TOP 250 doc_Main.Id,doc_Main.Gid,doc_Main.Name,doc_Main.TimeEnter,doc_Main.Prio,doc_Main.Direction,
doc_Main.Status,doc_Main.CreaterId,doc_Main.Subject,doc_Main.BodyType,doc_Main.Attach,doc_Main.FromAddr,doc_Main.ToAddr
,doc_Main.Gid_LineSet,doc_Main.XML

 
 FROM doc_Main
 

 WHERE
(doc_Main.Id_RoleSet IN (1,2,....) AND
((CONTAINS((doc_Main.Subject, doc_Main.Body), '"bulk"'))

 ORDER BY doc_Main.TimeEnter DESC


doc_main table is a big one with over 6 million records.

I have tried different combinations of clustered indexes and nonclustered indexes after reading on the internet but still i can't find the right combination.

The problem is that if i define some indexes or forced to use some it will work fine if the word searched in the full text catalog is very often present in the table but not when it has few appearances. If i change those indexes or define others it starts to work for few appearances but not for many.

Please help me to find the right approach to find out which indexes and statistics have to be created on this table to work fast in all cases.
NordicitAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Peter HutchisonSenior Network Systems SpecialistCommented:
A database can only only have one clustered index (which contains data) and upto 249 non-clustered indexes (contains pointers to data). Having any index will always speed up queries as it doesn't have to trawl through the entire table.
The best way to optimize indexes is to use the DAtabase Engine Tuning Advisor to find out what indexes you need.
0
NordicitAuthor Commented:
i have tried different combination of clustered and  non clustered indexes. Also have tried to use Database Engine Tuning Advisor. It doesn't show any improvements that can be made.

I will try to explain in more details:

If are many matches done by the full text catalog than the optimal execution would be to scan through the clustered index which has the first column Time enter and match the result of full text catalaog.

If are few matches done by the full text catalog than the optimal execution would be to seek through a non clustered index which has the first column Id(second Id_RoleSet and third TimeEnter desc) and match the results of full text catalog.

If I force the queries using with(index()) than the queries perform optimal. But for me is impossible to know in general if a word is often present in the table.

Another approach that i have tried is to use parameter sniffing. So when the query is executed the sql would include the search keyword in the execution plan  decision algorithm.

Thanks for your reply and hope that the problem is more clear now
0
Anthony PerkinsCommented:
How many items do you expect in the IN clause?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

NordicitAuthor Commented:
Maximum 6300 but in average 3000. That part is quite optimal in all cases.

In the execution plan is always high the cost of the full text catalog search in conjunction with one of the indexes.
0
Anthony PerkinsCommented:
Maximum 6300 but in average 3000. That part is quite optimal in all cases.
I would look into saving that many items into a table, so that you can JOIN against it instead of using IN.  This way you can build a non-dynamic query (preferably in a Stored Procedure) that will always give you consistent and above par results as it can re-use the same plan over and over again.
0
NordicitAuthor Commented:
We are doing that already i just didn't include that part so it looks more clear the problematic part.

I think I found a solution. I will post after additional testing if it proves to be the correct one.

Thanks again for your help.
0
Scott PletcherSenior DBACommented:
For this specific query, you'd want the clustered index to be on:
Id_RoleSet

To speed up the text searching, you could also consider "pre-searching" common phrases.   I suggest using bit masks in an int, or smallint, column for that.  

And/or you could cache previous search results using a separate table, in case the same text searches are done multiple times.
0
NordicitAuthor Commented:
This is the query that works in most cases optimal now

create table #docs (Id  int)

insert into #docs
select doc_main.Id
from doc_Main
where Id_RoleSet in (1,2,..........)
      and
      (
      CONTAINS((doc_Main.Subject, doc_Main.Body), '"regards"')  
      )

create nonclustered index temp_docs on #docs(Id)

SELECT TOP 250 doc_Main.Id,doc_Main.Gid,doc_Main.Name,doc_Main.TimeEnter,doc_Main.Prio,doc_Main.Direction,doc_Main.Status,doc_Main.CreaterId,doc_Main.Subject, doc_Main.Body,
doc_Main.BodyType,doc_Main.Attach,doc_Main.FromAddr,doc_Main.ToAddr,doc_Main.Gid_LineSet,doc_Main.XML, COALESCE(doc_Attrib.IsRead,0) as DocRead ,
(SELECT Ref FROM doc_Ref WHERE doc_Ref.Id_Doc=doc_Main.Id And doc_Ref.RefType= 2) as ExtraField2  

FROM doc_Main
      LEFT JOIN doc_Attrib ON doc_Main.Id = doc_Attrib.Id_Doc AND doc_Attrib.Gid_User = '{c6358127-8944-48dc-a8df-7a6da3826cee}'       
WHERE
       doc_Main.Id in (select Id
      from #docs
      
       )
ORDER BY doc_Main.TimeEnter DESC
--option(recompile)

drop table #docs


It looks extremely ugly.

I have tried with Id_RoleSet as clustered index but it does not help a lot.

Another limitation set for all the queries in the system is that there is a timeout of 30 seconds. Which i would like to keep. So if it would take more than 30 seconds anyway there is no way to cache because the query is canceled. If is under 30 than no need.

Thanks for your advice.
0
Anthony PerkinsCommented:
I would make the following changes:
CREATE TABLE #docs (Id int NOT NULL)

INSERT  INTO #docs (Id)
        SELECT  DISTINCT 
		m.Id
        FROM    doc_Main
        WHERE   Id_RoleSet IN (1, 2, ...)
                AND CONTAINS ((m.[Subject], m.Body), '"regards"')

CREATE UNIQUE CLUSTERED INDEX temp_docs ON #docs(Id)

SELECT TOP 250
        m.Id,
        m.Gid,
        m.Name,
        m.TimeEnter,
        m.Prio,
        m.Direction,
        m.[Status],
        m.CreaterId,
        m.Subject,
        m.Body,
        m.BodyType,
        m.[Attach],
        m.FromAddr,
        m.ToAddr,
        m.Gid_LineSet,
        m.[XML],
        COALESCE(a.IsRead, 0) AS DocRead,
        Ref AS ExtraField2
FROM    doc_Main m
	INNER JOIN #docs d ON m.Id = d.Id
        LEFT JOIN doc_Attrib a ON m.Id = a.Id_Doc
                                AND a.Gid_User = '{c6358127-8944-48dc-a8df-7a6da3826cee}'
	-- If possible, change the following to an INNER JOIN  
	-- and put the r.RefType = 2 the condition in the WHERE clause.
        LEFT JOIN doc_Ref r ON m.Id = r.Id_Doc AND r.RefType = 2
ORDER BY m.TimeEnter DESC 

DROP TABLE #docs

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
NordicitAuthor Commented:
It works really nice. Thank you. I will do some additional tests tomorrow.
CREATE UNIQUE CLUSTERED INDEX temp_docs ON #docs(Id)
I have replaced it with
CREATE UNIQUE NONCLUSTERED INDEX temp_docs ON #docs(Id)

it looks that the clustered index on temp table is much more expensive and is not needed in this cases as far as i can see.
0
Anthony PerkinsCommented:
it looks that the clustered index on temp table is much more expensive and is not needed in this cases as far as i can see.
It is fundamental to achieve best performance.  But you are the best judge of that.
0
NordicitAuthor Commented:
Thanks for your help. It works well in most of the cases.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.