views:

77

answers:

1

Email Match field = '@hotmail.com'

Email Match field entered: Results 1199 - speed of return 40 seconds

Email Match field not entered: Results 429 - speed of return 1.6 seconds

SELECT * FROM emails e where e.[From] like '%@hotmail.com%' OR e.[To] like '%@hotmail.com%'order by [id] DESC

I have to use % at start and end because i want to search this in email addresses

Thanks

Edit: alt text

alt text

alt text

Execution plan of original query

+1  A: 

Indexing and statistics is always the first thing you want to look at when optimizing performance, but for a more general approach targeting that exact query:

The OR clause will actually divide the query into two queries, one checking for each criteria, execute both, and then merge the results and filter out duplicates.

You might gain performance by a query such as

SELECT * FROM emails e
WHERE (e.From + '/' + e.To) LIKE '%@hotmail.com%'
ORDER BY id DESC

... although it's a bit uglier =) Try it out in your query analyzer and see what performs best...

EDIT

As Martin pointed out in comments, if the fields are nullable, the WHERE clause should have to be updated to accommodate that:

WHERE ( ISNULL(e.From,'') + '/' + ISNULL(e.To,'') ) LIKE '%@hotmail.com%'
David Hedlund
I doubt this bit about the `or` clause will be true. It will just do a single clustered index scan. The query returns all columns anyway.
Martin Smith
Yes this took half time to load result i have about 438605 records in table
@user467710 What do the execution plans look like for the 2 versions? And what is the structure of your table and indexes? Remember to take account that concatenating NULL yields NULL so this query will need adjustment.
Martin Smith
@Martin: Ah, ISNULL padding in case of nullable fiels is a very valid point! (although it might not make much sense for an `emails` table to have either of those fields nullable -- or perhaps for drafts? -- i have edited the answer accordingly)
David Hedlund
@David +1 but @user467710 I'm still interested in what the execution plans look like.
Martin Smith
I am not able to upload execution plan image/files because i don't have enough points.
If you could screenshot the execution plan before and after the change, and upload to something like http://imgur.com/ and paste the links in a comment here, that would still be useful to us :)
David Hedlund
I have added images for execution plan.
Search results are again slow because in table records keeps on adding.