Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find string by substring in SQL?

Tags:

I have huge table with 2 columns: Id and Title. Id is bigint and I'm free to choose type of Title column: varchar, char, text, whatever. Column Title contains random text strings like "abcdefg", "q", "allyourbasebelongtous" with maximum of 255 chars.

My task is to get strings by given substring. Substrings also have random length and can be start, middle or end of strings. The most obvious way to perform it:

SELECT * FROM t LIKE '%abc%' 

I don't care about INSERT, I need only to do fast selects. What can I do to perform search as fast as possible?

I use MS SQL Server 2008 R2, full text search will be useless, as far as I see.

like image 645
msergey Avatar asked Jul 11 '11 14:07

msergey


People also ask

Is substring faster than left?

According to the results, on nonindexed columns, LEFT/RIGHT are consistently faster than SUBSTRING.

How do I find the shortest and longest string in SQL?

SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends);


1 Answers

if you dont care about storage, then you can create another table with partial Title entries, beginning with each substring (up to 255 entries per normal title ).

in this way, you can index these substrings, and match only to the beginning of the string, should greatly improve performance.

like image 99
Randy Avatar answered Sep 19 '22 03:09

Randy