views:

181

answers:

3

How can queries like

SELECT * FROM sometable WHERE somefield LIKE '%value%'

be optimized?

The main issue here is the first wildcard which prevents DBMS from using index.

Edit: What is more, somefield value is solid string (not a piece of text) so fulltext search could not be performed.

+2  A: 

Use Full Text Search. The "Initial Idea" heading has the same example and leads to worked example solution.

And the MySQL docs

Edit: It can't be tuned in SQL itself. Using functions like LOCATE or PATINEX won't help either.

gbn
actually I don't need to find some specific word in text. I need to find substring in value (I'll update question to clarify this).
Jonas
It doesn't matter whether whole word or not: you can *not* optimise this query
gbn
Maybe there are more complex solutions than just optimizing query to perform this type of search faster.
Jonas
+1  A: 

It won't make a huge difference, given your problem is with the wildcard, but not using "SELECT *" will improve query performance. If you're not actually using all the fields you get back, that's a win and "SELECT *" causes two queries to fire, one to look up the fields for the table and then your query with the field names added in.

Tom
+1  A: 

Two ways:

(1) use an in-memory table so it goes very fast.

(2) cook up a better index and search algorithm than foo LIKE '%bar%'. It's not possible to make any suggestions about this without knowing more about your problem.

As you have pointed out, the %bar% pattern guarantees a table-scan for every lookup, which nullifies any possible search ingenuity in the database software.

Ollie Jones