Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why is "Like" faster than "=" 1

Status
Not open for further replies.

VB400

Programmer
Sep 8, 1999
359
US

I have a query that selects records based on LastName and FirstName (the table has an index by LastName, FirstName):

SELECT * FROM CUSTOMERS WHERE LastName = 'Smith' AND FirstName = 'Susan'

This takes an average of 24 seconds to return 88 records

If I change the SQL statement to:

SELECT * FROM CUSTOMERS WHERE LastName = 'Smith' AND FirstName LIKE 'Susan'

It then takes less than one second to return the same data -- No other parameters are involved.

What is it that causes this? Tarek
 
In Query Analyzer, select "Display Estimated Execution Plan" for each query and see where if and how the queries use the indexes. You'll be able to see where the bottlenecks occur in each query - find the steps with highest cost. Terry

The reason why worry kills more people than work is that more people worry than work. - Robert Frost
 

Terry,

I just did that and there is a difference:

When I use "=", SQL Server uses Table Scan

When I use "Like", SQL Server uses Index Seek, Filter and Bookmark Lookup

Why is this happening? Tarek
 
Those are the results I would expect. What I don't expect is the timing difference. Run UPDATE STATISTICS tablename and see if that makes a difference. Terry

The reason why worry kills more people than work is that more people worry than work. - Robert Frost
 

That didn't seem to help! However, I changed the index to be clustered and that made all the difference in the world.

Is this the right thing to do? I'm new to SQL Server so I'm not yet familiar with the "Standard Operating Procedures". It is my understanding that you can only have one clustered index and since this index is my main/only way of searching for customers, it seems logical to cluster this index.

Any thoughts/advise on that? Tarek
 
Usually, it makes sense to have a clustered index on the most frequently searched columns. I think I understand now why the query was taking so long. Seeking on the non-clustered index obtained pointers to the data. SQL then had to get the data pages. With the clustered index the index and data are on the same page. Terry

The reason why worry kills more people than work is that more people worry than work. - Robert Frost
 

So, eventhough it was trial and error on my part, it seems to have been the right solution in this case!

-- I knew that -- X-)

Thanks for your help Terry Tarek
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top